-
Notifications
You must be signed in to change notification settings - Fork 188
/
TaskQuartzImpl.java
3245 lines (2758 loc) · 110 KB
/
TaskQuartzImpl.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 com.evolveum.midpoint.prism.Containerable;
import com.evolveum.midpoint.prism.Item;
import com.evolveum.midpoint.prism.PrismContainer;
import com.evolveum.midpoint.prism.PrismContainerDefinition;
import com.evolveum.midpoint.prism.PrismContainerValue;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismObjectDefinition;
import com.evolveum.midpoint.prism.PrismProperty;
import com.evolveum.midpoint.prism.PrismPropertyDefinition;
import com.evolveum.midpoint.prism.PrismPropertyValue;
import com.evolveum.midpoint.prism.PrismReference;
import com.evolveum.midpoint.prism.PrismReferenceDefinition;
import com.evolveum.midpoint.prism.PrismReferenceValue;
import com.evolveum.midpoint.prism.PrismValue;
import com.evolveum.midpoint.prism.delta.ChangeType;
import com.evolveum.midpoint.prism.delta.ContainerDelta;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.PropertyDelta;
import com.evolveum.midpoint.prism.delta.ReferenceDelta;
import com.evolveum.midpoint.prism.delta.builder.DeltaBuilder;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.builder.QueryBuilder;
import com.evolveum.midpoint.prism.util.CloneUtil;
import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import com.evolveum.midpoint.repo.api.ModificationPrecondition;
import com.evolveum.midpoint.repo.api.PreconditionViolationException;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.schema.DeltaConvertor;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.statistics.EnvironmentalPerformanceInformation;
import com.evolveum.midpoint.schema.statistics.IterativeTaskInformation;
import com.evolveum.midpoint.schema.statistics.ProvisioningOperation;
import com.evolveum.midpoint.schema.statistics.ActionsExecutedInformation;
import com.evolveum.midpoint.schema.statistics.StatisticsUtil;
import com.evolveum.midpoint.schema.statistics.SynchronizationInformation;
import com.evolveum.midpoint.task.api.*;
import com.evolveum.midpoint.task.quartzimpl.handlers.WaitForSubtasksByPollingTaskHandler;
import com.evolveum.midpoint.task.quartzimpl.handlers.WaitForTasksTaskHandler;
import com.evolveum.midpoint.util.DebugUtil;
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.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.midpoint.xml.ns._public.common.common_3.*;
import com.evolveum.prism.xml.ns._public.types_3.ItemDeltaType;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import java.util.*;
import java.util.concurrent.Future;
import static com.evolveum.midpoint.prism.xml.XmlTypeConverter.createXMLGregorianCalendar;
import static com.evolveum.midpoint.schema.GetOperationOptions.retrieveItemsNamed;
import static com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType.F_MODEL_OPERATION_CONTEXT;
import static com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType.F_WORKFLOW_CONTEXT;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singleton;
import static org.apache.commons.collections4.CollectionUtils.addIgnoreNull;
/**
* Implementation of a Task.
*
* @see TaskManagerQuartzImpl
*
* Target state (not quite reached as for now): Functionality present in Task is related to the
* data structure describing the task itself, i.e. to the embedded TaskType prism and accompanying data.
* Everything related to the management of tasks is put into TaskManagerQuartzImpl and its helper classes.
*
* @author Radovan Semancik
* @author Pavol Mederly
*
*/
public class TaskQuartzImpl implements Task {
public static final String DOT_INTERFACE = Task.class.getName() + ".";
private TaskBinding DEFAULT_BINDING_TYPE = TaskBinding.TIGHT;
private static final int TIGHT_BINDING_INTERVAL_LIMIT = 10;
public static final long DEFAULT_OPERATION_STATS_UPDATE_INTERVAL = 3000L;
private Long lastOperationStatsUpdateTimestamp;
private long operationStatsUpdateInterval = DEFAULT_OPERATION_STATS_UPDATE_INTERVAL;
private PrismObject<TaskType> taskPrism;
private PrismObject<UserType> requestee; // temporary information
private EnvironmentalPerformanceInformation environmentalPerformanceInformation = new EnvironmentalPerformanceInformation();
private SynchronizationInformation synchronizationInformation; // has to be explicitly enabled
private IterativeTaskInformation iterativeTaskInformation; // has to be explicitly enabled
private ActionsExecutedInformation actionsExecutedInformation; // has to be explicitly enabled
/**
* Lightweight asynchronous subtasks.
* Each task here is a LAT, i.e. transient and with assigned lightweight handler.
* <p>
* This must be synchronized, because interrupt() method uses it.
*/
private Set<TaskQuartzImpl> lightweightAsynchronousSubtasks = Collections.synchronizedSet(new HashSet<TaskQuartzImpl>());
private Task parentForLightweightAsynchronousTask; // EXPERIMENTAL
/*
* Task result is stored here as well as in task prism.
*
* This one is the live value of this task's result. All operations working with this task
* should work with this value. This value is explicitly updated from the value in prism
* when fetching task from repo (or creating anew).
*
* The value in taskPrism is updated when necessary, e.g. when getting taskPrism
* (for example, used when persisting task to repo), etc, see the code.
*
* Note that this means that we SHOULD NOT get operation result from the prism - we should
* use task.getResult() instead!
*
* This result can be null if the task was created from taskPrism retrieved from repo without fetching the result.
* Such tasks should NOT be used to execute handlers, as the result information would be lost.
*
* Basically, the result should be initialized only when a new transient task is created. It should be then persisted
* into the repository. Tasks that are to execute handlers should be fetched from the repository with their results.
*/
private OperationResult taskResult;
/**
* Is the task handler allowed to run, or should it stop as soon as possible?
*/
private volatile boolean canRun;
private TaskManagerQuartzImpl taskManager;
private RepositoryService repositoryService;
/**
* The code that should be run for asynchronous transient tasks.
* (As opposed to asynchronous persistent tasks, where the handler is specified
* via Handler URI in task prism object.)
*/
private LightweightTaskHandler lightweightTaskHandler;
/**
* Future representing executing (or submitted-to-execution) lightweight task handler.
*/
private Future lightweightHandlerFuture;
/**
* An indication whether lighweight hander is currently executing or not.
* Used for waiting upon its completion (because java.util.concurrent facilities are not able
* to show this for cancelled/interrupted tasks).
*/
private volatile boolean lightweightHandlerExecuting;
private static final Trace LOGGER = TraceManager.getTrace(TaskQuartzImpl.class);
private static final Trace PERFORMANCE_ADVISOR = TraceManager.getPerformanceAdvisorTrace();
private TaskQuartzImpl(TaskManagerQuartzImpl taskManager) {
this.taskManager = taskManager;
this.canRun = true;
}
//region Constructors
/**
* Note: This constructor assumes that the task is transient.
*
* @param taskManager
* @param taskIdentifier
* @param operationName if null, default op. name will be used
*/
TaskQuartzImpl(TaskManagerQuartzImpl taskManager, LightweightIdentifier taskIdentifier, String operationName) {
this(taskManager);
this.repositoryService = taskManager.getRepositoryService();
this.taskPrism = createPrism();
setTaskIdentifier(taskIdentifier.toString());
setExecutionStatusTransient(TaskExecutionStatus.RUNNABLE);
setRecurrenceStatusTransient(TaskRecurrence.SINGLE);
setBindingTransient(DEFAULT_BINDING_TYPE);
setProgressTransient(0);
setObjectTransient(null);
createOrUpdateTaskResult(operationName, true);
setDefaults();
}
/**
* Assumes that the task is persistent
*
* NOTE: if the result in prism is null, task result will be kept null as well (meaning it was not fetched from the repository).
*
* @param operationName if null, default op. name will be used
*/
TaskQuartzImpl(TaskManagerQuartzImpl taskManager, PrismObject<TaskType> taskPrism, RepositoryService repositoryService,
String operationName) {
this(taskManager);
this.repositoryService = repositoryService;
this.taskPrism = taskPrism;
createOrUpdateTaskResult(operationName, false);
setDefaults();
}
private PrismObject<TaskType> createPrism() {
try {
return getPrismContext().createObject(TaskType.class);
} catch (SchemaException e) {
throw new SystemException(e.getMessage(), e);
}
}
private void setDefaults() {
if (getBinding() == null) {
setBindingTransient(DEFAULT_BINDING_TYPE);
}
}
private void createOrUpdateTaskResult(String operationName, boolean create) {
OperationResultType resultInPrism = taskPrism.asObjectable().getResult();
if (resultInPrism == null && create) {
if (operationName == null) {
resultInPrism = createUnnamedTaskResult().createOperationResultType();
} else {
resultInPrism = new OperationResult(operationName).createOperationResultType();
}
taskPrism.asObjectable().setResult(resultInPrism);
}
if (resultInPrism != null) {
try {
taskResult = OperationResult.createOperationResult(resultInPrism);
} catch (SchemaException e) {
throw new SystemException(e.getMessage(), e);
}
}
}
//endregion
public PrismObject<TaskType> getTaskPrismObject() {
if (taskResult != null) {
taskPrism.asObjectable().setResult(taskResult.createOperationResultType());
taskPrism.asObjectable().setResultStatus(taskResult.getStatus().createStatusType());
}
return taskPrism;
}
@Override
public TaskType getTaskType() {
return getTaskPrismObject().asObjectable();
}
RepositoryService getRepositoryService() {
return repositoryService;
}
void setRepositoryService(RepositoryService repositoryService) {
this.repositoryService = repositoryService;
}
@Override
public boolean isAsynchronous() {
return getPersistenceStatus() == TaskPersistenceStatus.PERSISTENT
|| isLightweightAsynchronousTask(); // note: if it has lightweight task handler, it must be transient
}
private boolean recreateQuartzTrigger = false; // whether to recreate quartz trigger on next savePendingModifications and/or synchronizeWithQuartz
public boolean isRecreateQuartzTrigger() {
return recreateQuartzTrigger;
}
public void setRecreateQuartzTrigger(boolean recreateQuartzTrigger) {
this.recreateQuartzTrigger = recreateQuartzTrigger;
}
@NotNull
private final Collection<ItemDelta<?, ?>> pendingModifications = new ArrayList<>();
public void addPendingModification(ItemDelta<?, ?> delta) {
ItemDelta.merge(pendingModifications, delta);
}
@Override
public void addModification(ItemDelta<?, ?> delta) throws SchemaException {
addPendingModification(delta);
delta.applyTo(taskPrism);
}
@Override
public void addModifications(Collection<ItemDelta<?, ?>> deltas) throws SchemaException {
for (ItemDelta<?, ?> delta : deltas) {
addPendingModification(delta);
delta.applyTo(taskPrism);
}
}
@Override
public void addModificationImmediate(ItemDelta<?, ?> delta, OperationResult parentResult)
throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException {
addPendingModification(delta);
delta.applyTo(taskPrism);
savePendingModifications(parentResult);
}
@Override
public void savePendingModifications(OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
if (isTransient()) {
synchronized (pendingModifications) {
pendingModifications.clear();
}
return;
}
synchronized (pendingModifications) { // todo perhaps we should put something like this at more places here...
if (!pendingModifications.isEmpty()) {
try {
repositoryService.modifyObject(TaskType.class, getOid(), pendingModifications, parentResult);
} finally { // todo reconsider this (it's not ideal but we need at least to reset pendingModifications to stop repeating applying this change)
synchronizeWithQuartzIfNeeded(pendingModifications, parentResult);
pendingModifications.clear();
}
}
}
if (isRecreateQuartzTrigger()) {
synchronizeWithQuartz(parentResult);
}
}
@Override
@NotNull
public Collection<ItemDelta<?, ?>> getPendingModifications() {
return pendingModifications;
}
public void synchronizeWithQuartz(OperationResult parentResult) {
taskManager.synchronizeTaskWithQuartz(this, parentResult);
setRecreateQuartzTrigger(false);
}
private static Set<QName> quartzRelatedProperties = new HashSet<>();
static {
quartzRelatedProperties.add(TaskType.F_BINDING);
quartzRelatedProperties.add(TaskType.F_RECURRENCE);
quartzRelatedProperties.add(TaskType.F_SCHEDULE);
quartzRelatedProperties.add(TaskType.F_HANDLER_URI);
}
private void synchronizeWithQuartzIfNeeded(Collection<ItemDelta<?, ?>> deltas, OperationResult parentResult) {
if (isRecreateQuartzTrigger()) {
synchronizeWithQuartz(parentResult);
return;
}
for (ItemDelta<?, ?> delta : deltas) {
if (delta.getParentPath().isEmpty() && quartzRelatedProperties.contains(delta.getElementName())) {
synchronizeWithQuartz(parentResult);
return;
}
}
}
private void processModificationNow(ItemDelta<?, ?> delta, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
if (delta != null) {
processModificationsNow(singleton(delta), parentResult);
}
}
private void processModificationsNow(Collection<ItemDelta<?, ?>> deltas, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
if (isPersistent()) {
repositoryService.modifyObject(TaskType.class, getOid(), deltas, parentResult);
synchronizeWithQuartzIfNeeded(deltas, parentResult);
}
}
private void processModificationsNow(Collection<ItemDelta<?, ?>> deltas, ModificationPrecondition<TaskType> precondition, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException, PreconditionViolationException {
if (isPersistent()) {
repositoryService.modifyObject(TaskType.class, getOid(), deltas, precondition, null, parentResult);
synchronizeWithQuartzIfNeeded(deltas, parentResult);
}
}
private void processModificationBatched(ItemDelta<?, ?> delta) {
if (delta != null) {
addPendingModification(delta);
}
}
/*
* Getters and setters
* ===================
*/
/*
* Progress / expectedTotal
*/
@Override
public long getProgress() {
Long value = taskPrism.getPropertyRealValue(TaskType.F_PROGRESS, Long.class);
return value != null ? value : 0;
}
@Override
public void setProgress(long value) {
processModificationBatched(setProgressAndPrepareDelta(value));
}
@Override
public void setProgressImmediate(long value, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException {
try {
processModificationNow(setProgressAndPrepareDelta(value), parentResult);
} catch (ObjectAlreadyExistsException ex) {
throw new SystemException(ex);
}
}
@Override
public void setProgressTransient(long value) {
try {
taskPrism.setPropertyRealValue(TaskType.F_PROGRESS, value);
} catch (SchemaException e) {
// This should not happen
throw new IllegalStateException("Internal schema error: " + e.getMessage(), e);
}
}
private PropertyDelta<?> setProgressAndPrepareDelta(long value) {
setProgressTransient(value);
return createProgressDelta(value);
}
@Nullable
private PropertyDelta<?> createProgressDelta(long value) {
return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta(
taskManager.getTaskObjectDefinition(), TaskType.F_PROGRESS, value) : null;
}
@Override
public OperationStatsType getStoredOperationStats() {
return taskPrism.asObjectable().getOperationStats();
}
public void setOperationStatsTransient(OperationStatsType value) {
try {
taskPrism.setPropertyRealValue(TaskType.F_OPERATION_STATS, value);
} catch (SchemaException e) {
// This should not happen
throw new IllegalStateException("Internal schema error: " + e.getMessage(), e);
}
}
public void setOperationStats(OperationStatsType value) {
processModificationBatched(setOperationStatsAndPrepareDelta(value));
}
private PropertyDelta<?> setOperationStatsAndPrepareDelta(OperationStatsType value) {
setOperationStatsTransient(value);
return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta(
taskManager.getTaskObjectDefinition(), TaskType.F_OPERATION_STATS, value) : null;
}
@Override
@Nullable
public Long getExpectedTotal() {
return taskPrism.getPropertyRealValue(TaskType.F_EXPECTED_TOTAL, Long.class);
}
@Override
public void setExpectedTotal(Long value) {
processModificationBatched(setExpectedTotalAndPrepareDelta(value));
}
@Override
public void setExpectedTotalImmediate(Long value, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException {
try {
processModificationNow(setExpectedTotalAndPrepareDelta(value), parentResult);
} catch (ObjectAlreadyExistsException ex) {
throw new SystemException(ex);
}
}
public void setExpectedTotalTransient(Long value) {
try {
taskPrism.setPropertyRealValue(TaskType.F_EXPECTED_TOTAL, value);
} catch (SchemaException e) {
// This should not happen
throw new IllegalStateException("Internal schema error: " + e.getMessage(), e);
}
}
private PropertyDelta<?> setExpectedTotalAndPrepareDelta(Long value) {
setExpectedTotalTransient(value);
return createExpectedTotalDelta(value);
}
@Nullable
private PropertyDelta<?> createExpectedTotalDelta(Long value) {
return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta(
taskManager.getTaskObjectDefinition(), TaskType.F_EXPECTED_TOTAL, value) : null;
}
/*
* Result
*
* setters set also result status type!
*/
@Override
public OperationResult getResult() {
return taskResult;
}
@Override
public void setResult(OperationResult result) {
processModificationBatched(setResultAndPrepareDelta(result));
setResultStatusType(result != null ? result.getStatus().createStatusType() : null);
}
@Override
public void setResultImmediate(OperationResult result, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException {
try {
processModificationNow(setResultAndPrepareDelta(result), parentResult);
setResultStatusTypeImmediate(result != null ? result.getStatus().createStatusType() : null, parentResult);
} catch (ObjectAlreadyExistsException ex) {
throw new SystemException(ex);
}
}
public void updateStoredTaskResult() throws SchemaException, ObjectNotFoundException {
setResultImmediate(getResult(), new OperationResult("dummy"));
}
public void setResultTransient(OperationResult result) {
this.taskResult = result;
this.taskPrism.asObjectable().setResult(result != null ? result.createOperationResultType() : null);
setResultStatusTypeTransient(result != null ? result.getStatus().createStatusType() : null);
}
private PropertyDelta<?> setResultAndPrepareDelta(OperationResult result) {
setResultTransient(result);
if (isPersistent()) {
return PropertyDelta.createReplaceDeltaOrEmptyDelta(taskManager.getTaskObjectDefinition(),
TaskType.F_RESULT, result != null ? result.createOperationResultType() : null);
} else {
return null;
}
}
/*
* Result status
*
* We read the status from current 'taskResult', not from prism - to be sure to get the most current value.
* However, when updating, we update the result in prism object in order for the result to be stored correctly in
* the repo (useful for displaying the result in task list).
*
* So, setting result type to a value that contradicts current taskResult leads to problems.
* Anyway, result type should not be set directly, only when updating OperationResult.
*/
@Override
public OperationResultStatusType getResultStatus() {
if (taskResult == null) {
if (taskPrism != null) {
return taskPrism.asObjectable().getResultStatus();
} else {
return null;
}
} else {
return taskResult.getStatus().createStatusType();
}
}
public void setResultStatusType(OperationResultStatusType value) {
processModificationBatched(setResultStatusTypeAndPrepareDelta(value));
}
public void setResultStatusTypeImmediate(OperationResultStatusType value, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
processModificationNow(setResultStatusTypeAndPrepareDelta(value), parentResult);
}
public void setResultStatusTypeTransient(OperationResultStatusType value) {
taskPrism.asObjectable().setResultStatus(value);
}
private PropertyDelta<?> setResultStatusTypeAndPrepareDelta(OperationResultStatusType value) {
setResultStatusTypeTransient(value);
if (isPersistent()) {
return PropertyDelta.createReplaceDeltaOrEmptyDelta(taskManager.getTaskObjectDefinition(),
TaskType.F_RESULT_STATUS, value);
} else {
return null;
}
}
/*
* Handler URI
*/
@Override
public String getHandlerUri() {
return taskPrism.getPropertyRealValue(TaskType.F_HANDLER_URI, String.class);
}
public void setHandlerUriTransient(String handlerUri) {
try {
taskPrism.setPropertyRealValue(TaskType.F_HANDLER_URI, handlerUri);
} catch (SchemaException e) {
// This should not happen
throw new IllegalStateException("Internal schema error: " + e.getMessage(), e);
}
}
@Override
public void setHandlerUriImmediate(String value, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException {
try {
processModificationNow(setHandlerUriAndPrepareDelta(value), parentResult);
} catch (ObjectAlreadyExistsException ex) {
throw new SystemException(ex);
}
}
@Override
public void setHandlerUri(String value) {
processModificationBatched(setHandlerUriAndPrepareDelta(value));
}
private PropertyDelta<?> setHandlerUriAndPrepareDelta(String value) {
setHandlerUriTransient(value);
return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta(
taskManager.getTaskObjectDefinition(), TaskType.F_HANDLER_URI, value) : null;
}
/*
* Other handlers URI stack
*/
@Override
public UriStack getOtherHandlersUriStack() {
checkHandlerUriConsistency();
return taskPrism.asObjectable().getOtherHandlersUriStack();
}
public void setOtherHandlersUriStackTransient(UriStack value) {
try {
taskPrism.setPropertyRealValue(TaskType.F_OTHER_HANDLERS_URI_STACK, value);
} catch (SchemaException e) {
// This should not happen
throw new IllegalStateException("Internal schema error: " + e.getMessage(), e);
}
checkHandlerUriConsistency();
}
public void setOtherHandlersUriStackImmediate(UriStack value, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException {
try {
processModificationNow(setOtherHandlersUriStackAndPrepareDelta(value), parentResult);
checkHandlerUriConsistency();
} catch (ObjectAlreadyExistsException ex) {
throw new SystemException(ex);
}
}
public void setOtherHandlersUriStack(UriStack value) {
processModificationBatched(setOtherHandlersUriStackAndPrepareDelta(value));
checkHandlerUriConsistency();
}
private PropertyDelta<?> setOtherHandlersUriStackAndPrepareDelta(UriStack value) {
setOtherHandlersUriStackTransient(value);
return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta(
taskManager.getTaskObjectDefinition(), TaskType.F_OTHER_HANDLERS_URI_STACK, value) : null;
}
private UriStackEntry popFromOtherHandlersUriStack() {
checkHandlerUriConsistency();
UriStack stack = taskPrism.getPropertyRealValue(TaskType.F_OTHER_HANDLERS_URI_STACK, UriStack.class);
// is this a live value or a copy? (should be live)
if (stack == null || stack.getUriStackEntry().isEmpty())
throw new IllegalStateException("Couldn't pop from OtherHandlersUriStack, because it is null or empty");
int last = stack.getUriStackEntry().size() - 1;
UriStackEntry retval = stack.getUriStackEntry().get(last);
stack.getUriStackEntry().remove(last);
// UriStack stack2 = taskPrism.getPropertyRealValue(TaskType.F_OTHER_HANDLERS_URI_STACK, UriStack.class);
// LOGGER.info("Stack size after popping: " + stack.getUriStackEntry().size()
// + ", freshly got stack size: " + stack2.getUriStackEntry().size());
setOtherHandlersUriStack(stack);
return retval;
}
// @Override
// public void pushHandlerUri(String uri) {
// pushHandlerUri(uri, null, null);
// }
//
// @Override
// public void pushHandlerUri(String uri, ScheduleType schedule) {
// pushHandlerUri(uri, schedule, null);
// }
@Override
public void pushHandlerUri(String uri, ScheduleType schedule, TaskBinding binding) {
pushHandlerUri(uri, schedule, binding, (Collection<ItemDelta<?, ?>>) null);
}
@Override
public void pushHandlerUri(String uri, ScheduleType schedule, TaskBinding binding, ItemDelta<?, ?> delta) {
Collection<ItemDelta<?, ?>> deltas = null;
if (delta != null) {
deltas = new ArrayList<>();
deltas.add(delta);
}
pushHandlerUri(uri, schedule, binding, deltas);
}
/**
* Makes (uri, schedule, binding) the current task properties, and pushes current (uri, schedule, binding, extensionChange)
* onto the stack.
*
* @param uri New Handler URI
* @param schedule New schedule
* @param binding New binding
*/
@Override
public void pushHandlerUri(String uri, ScheduleType schedule, TaskBinding binding,
Collection<ItemDelta<?, ?>> extensionDeltas) {
Validate.notNull(uri);
if (binding == null) {
binding = bindingFromSchedule(schedule);
}
checkHandlerUriConsistency();
if (this.getHandlerUri() != null) {
UriStack stack = taskPrism.getPropertyRealValue(TaskType.F_OTHER_HANDLERS_URI_STACK, UriStack.class);
if (stack == null) {
stack = new UriStack();
}
UriStackEntry use = new UriStackEntry();
use.setHandlerUri(getHandlerUri());
use.setRecurrence(getRecurrenceStatus().toTaskType());
use.setSchedule(getSchedule());
use.setBinding(getBinding().toTaskType());
if (extensionDeltas != null) {
storeExtensionDeltas(use.getExtensionDelta(), extensionDeltas);
}
stack.getUriStackEntry().add(use);
setOtherHandlersUriStack(stack);
}
setHandlerUri(uri);
setSchedule(schedule);
setRecurrenceStatus(recurrenceFromSchedule(schedule));
setBinding(binding);
this.setRecreateQuartzTrigger(true); // will be applied on modifications save
}
public ItemDelta<?, ?> createExtensionDelta(PrismPropertyDefinition definition, Object realValue) {
PrismProperty<Object> property = (PrismProperty<Object>) definition.instantiate();
property.setRealValue(realValue);
// PropertyDelta propertyDelta = new PropertyDelta(new ItemPath(TaskType.F_EXTENSION, property.getElementName()), definition);
// propertyDelta.setValuesToReplace(PrismValue.cloneCollection(property.getValues()));
return PropertyDelta.createModificationReplaceProperty(new ItemPath(TaskType.F_EXTENSION, property.getElementName()), definition, realValue);
}
private void storeExtensionDeltas(List<ItemDeltaType> result, Collection<ItemDelta<?, ?>> extensionDeltas) {
for (ItemDelta itemDelta : extensionDeltas) {
Collection<ItemDeltaType> deltaTypes;
try {
deltaTypes = DeltaConvertor.toItemDeltaTypes(itemDelta);
} catch (SchemaException e) {
throw new SystemException("Unexpected SchemaException when converting extension ItemDelta to ItemDeltaType", e);
}
result.addAll(deltaTypes);
}
}
// derives default binding form schedule
private TaskBinding bindingFromSchedule(ScheduleType schedule) {
if (schedule == null) {
return DEFAULT_BINDING_TYPE;
} else if (schedule.getInterval() != null && schedule.getInterval() != 0) {
return schedule.getInterval() <= TIGHT_BINDING_INTERVAL_LIMIT ? TaskBinding.TIGHT : TaskBinding.LOOSE;
} else if (StringUtils.isNotEmpty(schedule.getCronLikePattern())) {
return TaskBinding.LOOSE;
} else {
return DEFAULT_BINDING_TYPE;
}
}
private TaskRecurrence recurrenceFromSchedule(ScheduleType schedule) {
if (schedule == null) {
return TaskRecurrence.SINGLE;
} else if (schedule.getInterval() != null && schedule.getInterval() != 0) {
return TaskRecurrence.RECURRING;
} else if (StringUtils.isNotEmpty(schedule.getCronLikePattern())) {
return TaskRecurrence.RECURRING;
} else {
return TaskRecurrence.SINGLE;
}
}
// @Override
// public void replaceCurrentHandlerUri(String newUri, ScheduleType schedule) {
//
// checkHandlerUriConsistency();
// setHandlerUri(newUri);
// setSchedule(schedule);
// }
@Override
public void finishHandler(OperationResult parentResult)
throws ObjectNotFoundException, SchemaException {
// let us drop the current handler URI and nominate the top of the other
// handlers stack as the current one
LOGGER.trace("finishHandler called for handler URI {}, task {}", this.getHandlerUri(), this);
UriStack otherHandlersUriStack = getOtherHandlersUriStack();
if (otherHandlersUriStack != null && !otherHandlersUriStack.getUriStackEntry().isEmpty()) {
UriStackEntry use = popFromOtherHandlersUriStack();
setHandlerUri(use.getHandlerUri());
setRecurrenceStatus(use.getRecurrence() != null ?
TaskRecurrence.fromTaskType(use.getRecurrence()) :
recurrenceFromSchedule(use.getSchedule()));
setSchedule(use.getSchedule());
if (use.getBinding() != null) {
setBinding(TaskBinding.fromTaskType(use.getBinding()));
} else {
setBinding(bindingFromSchedule(use.getSchedule()));
}
for (ItemDeltaType itemDeltaType : use.getExtensionDelta()) {
ItemDelta itemDelta = DeltaConvertor
.createItemDelta(itemDeltaType, TaskType.class, taskManager.getPrismContext());
LOGGER.trace("Applying ItemDelta to task extension; task = {}; itemDelta = {}", this, itemDelta.debugDump());
this.modifyExtension(itemDelta);
}
this.setRecreateQuartzTrigger(true);
} else {
//setHandlerUri(null); // we want the last handler to remain set so the task can be revived
taskManager.closeTaskWithoutSavingState(this, parentResult); // as there are no more handlers, let us close this task
}
try {
savePendingModifications(parentResult);
checkDependentTasksOnClose(parentResult);
} catch (ObjectAlreadyExistsException ex) {
throw new SystemException(ex);
}
LOGGER.trace("finishHandler: new current handler uri = {}, new number of handlers = {}", getHandlerUri(),
getHandlersCount());
}
public void checkDependentTasksOnClose(OperationResult result) throws SchemaException, ObjectNotFoundException {
//System.out.println("checkDependentTasksOnClose (state=" + getExecutionStatus()+"): " + this);
if (getExecutionStatus() != TaskExecutionStatus.CLOSED) {
return;
}
for (Task dependent : listDependents(result)) {
((TaskQuartzImpl) dependent).checkDependencies(result);
}
Task parentTask = getParentTask(result);
if (parentTask != null) {
((TaskQuartzImpl) parentTask).checkDependencies(result);
}
}
public void checkDependencies(OperationResult result) throws SchemaException, ObjectNotFoundException {
if (getExecutionStatus() != TaskExecutionStatus.WAITING || getWaitingReason() != TaskWaitingReason.OTHER_TASKS) {
//System.out.println("### WRONG STATE for checkDependencies for " + this);
return;
}
List<Task> dependencies = listSubtasks(result);
dependencies.addAll(listPrerequisiteTasks(result));
LOGGER.trace("Checking {} dependencies for waiting task {}", dependencies.size(), this);
for (Task dependency : dependencies) {
if (!dependency.isClosed()) {
LOGGER.trace("Dependency {} of {} is not closed (status = {})", dependency, this, dependency.getExecutionStatus());
return;
}
}
LOGGER.trace("All dependencies of {} are closed, unpausing the task", this);
try {
taskManager.unpauseTask(this, result);
} catch (PreconditionViolationException e) {
LoggingUtils.logUnexpectedException(LOGGER, "Task cannot be unpaused because it is no longer in WAITING state -- ignoring", e, this);
}
}
public int getHandlersCount() {
checkHandlerUriConsistency();
int main = getHandlerUri() != null ? 1 : 0;
int others = getOtherHandlersUriStack() != null ? getOtherHandlersUriStack().getUriStackEntry().size() : 0;
return main + others;
}
private boolean isOtherHandlersUriStackEmpty() {
UriStack stack = taskPrism.asObjectable().getOtherHandlersUriStack();
return stack == null || stack.getUriStackEntry().isEmpty();
}
private void checkHandlerUriConsistency() {
if (getHandlerUri() == null && !isOtherHandlersUriStackEmpty())
throw new IllegalStateException(
"Handler URI is null but there is at least one 'other' handler (otherHandlerUriStack size = "
+ getOtherHandlersUriStack().getUriStackEntry().size() + ")");
}
/*
* Persistence status
*/
@Override
public TaskPersistenceStatus getPersistenceStatus() {
return StringUtils.isEmpty(getOid()) ? TaskPersistenceStatus.TRANSIENT : TaskPersistenceStatus.PERSISTENT;
}
// public void setPersistenceStatusTransient(TaskPersistenceStatus persistenceStatus) {
// this.persistenceStatus = persistenceStatus;
// }
public boolean isPersistent() {
return getPersistenceStatus() == TaskPersistenceStatus.PERSISTENT;
}
@Override
public boolean isTransient() {
return getPersistenceStatus() == TaskPersistenceStatus.TRANSIENT;
}
/*
* Oid
*/
@Override
public String getOid() {
return taskPrism.getOid();
}
public void setOid(String oid) {
taskPrism.setOid(oid);