-
Notifications
You must be signed in to change notification settings - Fork 188
/
Clockwork.java
1601 lines (1453 loc) · 74.1 KB
/
Clockwork.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-2017 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.model.impl.lens;
import com.evolveum.midpoint.audit.api.AuditEventRecord;
import com.evolveum.midpoint.audit.api.AuditEventStage;
import com.evolveum.midpoint.audit.api.AuditEventType;
import com.evolveum.midpoint.audit.api.AuditService;
import com.evolveum.midpoint.common.Clock;
import com.evolveum.midpoint.model.api.ProgressInformation;
import com.evolveum.midpoint.model.impl.migrator.Migrator;
import com.evolveum.midpoint.repo.api.ConflictWatcher;
import com.evolveum.midpoint.repo.api.PreconditionViolationException;
import com.evolveum.midpoint.repo.common.expression.ExpressionFactory;
import com.evolveum.midpoint.repo.common.expression.ExpressionVariables;
import com.evolveum.midpoint.model.api.ModelAuthorizationAction;
import com.evolveum.midpoint.model.api.ModelExecuteOptions;
import com.evolveum.midpoint.model.api.context.ModelState;
import com.evolveum.midpoint.model.api.hooks.ChangeHook;
import com.evolveum.midpoint.model.api.hooks.HookOperationMode;
import com.evolveum.midpoint.model.api.hooks.HookRegistry;
import com.evolveum.midpoint.model.common.SystemObjectCache;
import com.evolveum.midpoint.model.common.expression.evaluator.caching.AssociationSearchExpressionEvaluatorCache;
import com.evolveum.midpoint.model.common.expression.script.ScriptExpression;
import com.evolveum.midpoint.model.common.expression.script.ScriptExpressionFactory;
import com.evolveum.midpoint.model.impl.ModelObjectResolver;
import com.evolveum.midpoint.model.impl.controller.ModelUtils;
import com.evolveum.midpoint.model.impl.lens.projector.ContextLoader;
import com.evolveum.midpoint.model.impl.lens.projector.Projector;
import com.evolveum.midpoint.model.impl.lens.projector.focus.FocusConstraintsChecker;
import com.evolveum.midpoint.model.impl.sync.RecomputeTaskHandler;
import com.evolveum.midpoint.model.impl.util.Utils;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.delta.*;
import com.evolveum.midpoint.prism.delta.builder.DeltaBuilder;
import com.evolveum.midpoint.prism.marshaller.QueryConvertor;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.query.ObjectFilter;
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.provisioning.api.ChangeNotificationDispatcher;
import com.evolveum.midpoint.provisioning.api.ProvisioningService;
import com.evolveum.midpoint.provisioning.api.ResourceObjectChangeListener;
import com.evolveum.midpoint.provisioning.api.ResourceOperationListener;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.schema.ObjectDeltaOperation;
import com.evolveum.midpoint.schema.constants.ExpressionConstants;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.internals.InternalsConfig;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.schema.util.SystemConfigurationTypeUtil;
import com.evolveum.midpoint.security.api.OwnerResolver;
import com.evolveum.midpoint.security.api.SecurityUtil;
import com.evolveum.midpoint.security.enforcer.api.AccessDecision;
import com.evolveum.midpoint.security.enforcer.api.AuthorizationParameters;
import com.evolveum.midpoint.security.enforcer.api.ObjectSecurityConstraints;
import com.evolveum.midpoint.security.enforcer.api.SecurityEnforcer;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskBinding;
import com.evolveum.midpoint.task.api.TaskCategory;
import com.evolveum.midpoint.task.api.TaskExecutionStatus;
import com.evolveum.midpoint.task.api.TaskManager;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.Holder;
import com.evolveum.midpoint.util.exception.AuthorizationException;
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.PolicyViolationException;
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.midpoint.xml.ns._public.common.common_3.*;
import com.evolveum.prism.xml.ns._public.query_3.QueryType;
import com.evolveum.prism.xml.ns._public.query_3.SearchFilterType;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.Validate;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import java.util.*;
import java.util.Map.Entry;
import static com.evolveum.midpoint.model.api.ProgressInformation.ActivityType.CLOCKWORK;
import static com.evolveum.midpoint.model.api.ProgressInformation.ActivityType.WAITING;
import static com.evolveum.midpoint.model.api.ProgressInformation.StateType.ENTERING;
import static com.evolveum.midpoint.model.api.ProgressInformation.StateType.EXITING;
import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
/**
* @author semancik
*
*/
@Component
public class Clockwork {
private static final int DEFAULT_NUMBER_OF_RESULTS_TO_KEEP = 5;
private static final int DEFAULT_MAX_CONFLICT_RESOLUTION_ATTEMPTS = 1; // synchronize with common-core-3.xsd
private static final int DEFAULT_CONFLICT_RESOLUTION_DELAY_UNIT = 5000; // synchronize with common-core-3.xsd
private static final int MAX_PRECONDITION_CONFLICT_RESOLUTION_ATTEMPTS = 3;
private static final Trace LOGGER = TraceManager.getTrace(Clockwork.class);
// This is ugly
// TODO: cleanup
@Autowired private Projector projector;
@Autowired private ContextLoader contextLoader;
@Autowired private ChangeExecutor changeExecutor;
@Autowired private AuditService auditService;
@Autowired private SecurityEnforcer securityEnforcer;
@Autowired private Clock clock;
@Autowired private ModelObjectResolver objectResolver;
@Autowired private SystemObjectCache systemObjectCache;
@Autowired private transient ProvisioningService provisioningService;
@Autowired private transient ChangeNotificationDispatcher changeNotificationDispatcher;
@Autowired private ExpressionFactory expressionFactory;
@Autowired private ScriptExpressionFactory scriptExpressionFactory;
@Autowired private PersonaProcessor personaProcessor;
@Autowired private PrismContext prismContext;
@Autowired private TaskManager taskManager;
@Autowired private OperationalDataManager metadataManager;
@Autowired private ContextFactory contextFactory;
@Autowired private Migrator migrator;
@Autowired(required = false)
private HookRegistry hookRegistry;
@Autowired
@Qualifier("cacheRepositoryService")
private transient RepositoryService repositoryService;
private LensDebugListener debugListener;
public LensDebugListener getDebugListener() {
return debugListener;
}
public void setDebugListener(LensDebugListener debugListener) {
this.debugListener = debugListener;
}
private static final int DEFAULT_MAX_CLICKS = 200;
public <F extends ObjectType> HookOperationMode run(LensContext<F> context, Task task, OperationResult result)
throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException,
ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException, PreconditionViolationException {
LOGGER.trace("Running clockwork for context {}", context);
if (InternalsConfig.consistencyChecks) {
context.checkConsistence();
}
int clicked = 0;
boolean focusConflictPresent = false;
HookOperationMode finalMode;
try {
context.reportProgress(new ProgressInformation(CLOCKWORK, ENTERING));
if (context.getFocusContext() != null && context.getFocusContext().getOid() != null) {
context.createAndRegisterConflictWatcher(context.getFocusContext().getOid(), repositoryService);
}
FocusConstraintsChecker.enterCache();
enterAssociationSearchExpressionEvaluatorCache();
provisioningService.enterConstraintsCheckerCache();
while (context.getState() != ModelState.FINAL) {
// TODO implement in model context (as transient or even non-transient attribute) to allow for checking in more complex scenarios
int maxClicks = getMaxClicks(context, result);
if (clicked >= maxClicks) {
throw new IllegalStateException("Model operation took too many clicks (limit is " + maxClicks + "). Is there a cycle?");
}
clicked++;
HookOperationMode mode = click(context, task, result);
if (mode == HookOperationMode.BACKGROUND) {
result.recordInProgress();
return mode;
} else if (mode == HookOperationMode.ERROR) {
return mode;
}
}
// One last click in FINAL state
finalMode = click(context, task, result);
if (finalMode == HookOperationMode.FOREGROUND) {
focusConflictPresent = checkFocusConflicts(context, task, result);
}
} finally {
context.unregisterConflictWatchers(repositoryService);
FocusConstraintsChecker.exitCache();
exitAssociationSearchExpressionEvaluatorCache();
provisioningService.exitConstraintsCheckerCache();
context.reportProgress(new ProgressInformation(CLOCKWORK, EXITING));
}
// intentionally outside the "try-finally" block to start with clean caches
if (focusConflictPresent) {
assert finalMode == HookOperationMode.FOREGROUND;
finalMode = resolveFocusConflict(context, task, result);
} else if (context.getConflictResolutionAttemptNumber() > 0) {
LOGGER.info("Resolved update conflict on attempt number {}", context.getConflictResolutionAttemptNumber());
}
return finalMode;
}
private <F extends ObjectType> boolean checkFocusConflicts(LensContext<F> context, Task task, OperationResult result) {
for (ConflictWatcher watcher : context.getConflictWatchers()) {
if (repositoryService.hasConflict(watcher, result)) {
LOGGER.debug("Found modify-modify conflict on {}", watcher);
return true;
}
}
return false;
}
private <F extends ObjectType> HookOperationMode resolveFocusConflict(LensContext<F> context, Task task, OperationResult result)
throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, ConfigurationException,
CommunicationException, SecurityViolationException, PolicyViolationException, ObjectAlreadyExistsException {
ConflictResolutionType resolutionPolicy = ModelUtils.getConflictResolution(context);
if (resolutionPolicy == null || resolutionPolicy.getAction() == ConflictResolutionActionType.NONE) {
return HookOperationMode.FOREGROUND;
}
PrismObject<F> focusObject = context.getFocusContext() != null ? context.getFocusContext().getObjectAny() : null;
ModelExecuteOptions options = new ModelExecuteOptions();
switch (resolutionPolicy.getAction()) {
case FAIL: throw new SystemException("Conflict detected while updating " + focusObject);
case LOG:
LOGGER.warn("Conflict detected while updating {}", focusObject);
return HookOperationMode.FOREGROUND;
case RECOMPUTE:
break;
case RECONCILE:
options.setReconcile();
break;
default:
throw new IllegalStateException("Unsupported conflict resolution action: " + resolutionPolicy.getAction());
}
// so, recompute is the action
LOGGER.debug("CONFLICT: Conflict detected while updating {}, recomputing (options={})", focusObject, options);
if (context.getFocusContext() == null) {
LOGGER.warn("No focus context, not possible to resolve conflict by focus recomputation"); // should really never occur
return HookOperationMode.FOREGROUND;
}
String oid = context.getFocusContext().getOid();
if (oid == null) {
LOGGER.warn("No focus OID, not possible to resolve conflict by focus recomputation"); // should really never occur
return HookOperationMode.FOREGROUND;
}
Class<F> focusClass = context.getFocusContext().getObjectTypeClass();
if (focusClass == null) {
LOGGER.warn("Focus class not known, not possible to resolve conflict by focus recomputation"); // should really never occur
return HookOperationMode.FOREGROUND;
}
if (TaskType.class.isAssignableFrom(focusClass)) {
return HookOperationMode.FOREGROUND; // this is actually quite expected, so don't bother anyone with that
}
if (!FocusType.class.isAssignableFrom(focusClass)) {
LOGGER.warn("Focus is not of FocusType (it is {}); not possible to resolve conflict by focus recomputation", focusClass.getName());
return HookOperationMode.FOREGROUND;
}
ConflictResolutionType focusConflictResolution = new ConflictResolutionType();
focusConflictResolution.setAction(ConflictResolutionActionType.ERROR);
options.setFocusConflictResolution(focusConflictResolution);
int preconditionAttempts = 0;
while (true) {
int attemptOld = context.getConflictResolutionAttemptNumber();
int attemptNew = attemptOld + 1;
boolean shouldExecuteAttempt = shouldExecuteAttempt(context, resolutionPolicy, attemptNew);
if (!shouldExecuteAttempt) {
LOGGER.warn("CONFLICT: Couldn't resolve conflict even after {} resolution attempt(s), giving up.", attemptOld);
return HookOperationMode.FOREGROUND;
}
delay(context, resolutionPolicy, attemptNew + preconditionAttempts);
PrismObject<F> focus = repositoryService.getObject(focusClass, oid, null, result);
LensContext<FocusType> contextNew = contextFactory.createRecomputeContext(focus, options, task, result);
contextNew.setProgressListeners(new ArrayList<>(emptyIfNull(context.getProgressListeners())));
contextNew.setConflictResolutionAttemptNumber(attemptNew);
LOGGER.debug("CONFLICT: Recomputing {} as reaction to conflict (options={}, attempts={},{}, readVersion={})",
context.getFocusContext().getHumanReadableName(), options, attemptNew, preconditionAttempts, contextNew.getFocusContext().getObjectReadVersion());
try {
// this is a recursion; but limited to max attempts which should not be a large number
HookOperationMode hookOperationMode = run(contextNew, task, result);
// This may be in fact a giveup after recompute that was not able to cleanly proceed.
LOGGER.debug("CONFLICT: Clean recompute (or giveup) of {} achieved (options={}, attempts={},{})",
context.getFocusContext().getHumanReadableName(), options, attemptNew, preconditionAttempts);
return hookOperationMode;
} catch (PreconditionViolationException e) {
preconditionAttempts++;
LOGGER.debug("CONFLICT: Recompute precondition failed (attempt {}, precondition attempt {}), trying again", attemptNew, preconditionAttempts);
if (preconditionAttempts < MAX_PRECONDITION_CONFLICT_RESOLUTION_ATTEMPTS) {
continue;
}
LOGGER.warn("CONFLICT: Couldn't resolve conflict even after {} resolution attempt(s) and {} precondition attempts, giving up.",
attemptOld, preconditionAttempts);
return HookOperationMode.FOREGROUND;
}
}
}
private <F extends ObjectType> boolean shouldExecuteAttempt(LensContext<F> context, @NotNull ConflictResolutionType resolutionPolicy, int attemptNew) {
int maxAttempts = defaultIfNull(resolutionPolicy.getMaxAttempts(), DEFAULT_MAX_CONFLICT_RESOLUTION_ATTEMPTS);
if (attemptNew > maxAttempts) {
return false;
}
return true;
}
private <F extends ObjectType> void delay(LensContext<F> context, @NotNull ConflictResolutionType resolutionPolicy, int attempts) {
long delayUnit = defaultIfNull(resolutionPolicy.getDelayUnit(), DEFAULT_CONFLICT_RESOLUTION_DELAY_UNIT);
for (int i = 0; i < attempts; i++) {
delayUnit *= 2;
}
long delay = (long) (Math.random() * delayUnit);
String message = "CONFLICT: Waiting "+delay+" milliseconds before starting conflict resolution (delay exponent: "+attempts+")";
// TODO convey information about waiting time after some GUI mechanism for displaying it is available
// (showing text messages is currently really ugly)
context.reportProgress(new ProgressInformation(WAITING, EXITING));
LOGGER.debug(message);
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// ignore
}
context.reportProgress(new ProgressInformation(WAITING, EXITING));
}
private void enterAssociationSearchExpressionEvaluatorCache() {
AssociationSearchExpressionEvaluatorCache cache = AssociationSearchExpressionEvaluatorCache.enterCache();
AssociationSearchExpressionCacheInvalidator invalidator = new AssociationSearchExpressionCacheInvalidator(cache);
cache.setClientContextInformation(invalidator);
changeNotificationDispatcher.registerNotificationListener((ResourceObjectChangeListener) invalidator);
changeNotificationDispatcher.registerNotificationListener((ResourceOperationListener) invalidator);
}
private void exitAssociationSearchExpressionEvaluatorCache() {
AssociationSearchExpressionEvaluatorCache cache = AssociationSearchExpressionEvaluatorCache.exitCache();
if (cache == null) {
return; // shouldn't occur
}
Object invalidator = cache.getClientContextInformation();
if (invalidator == null || !(invalidator instanceof AssociationSearchExpressionCacheInvalidator)) {
return; // shouldn't occur either
}
changeNotificationDispatcher.unregisterNotificationListener((ResourceObjectChangeListener) invalidator);
changeNotificationDispatcher.unregisterNotificationListener((ResourceOperationListener) invalidator);
}
private <F extends ObjectType> int getMaxClicks(LensContext<F> context, OperationResult result) throws SchemaException, ObjectNotFoundException {
PrismObject<SystemConfigurationType> systemConfiguration = systemObjectCache.getSystemConfiguration(result);
Integer maxClicks = SystemConfigurationTypeUtil.getMaxModelClicks(systemConfiguration);
if (maxClicks == null) {
return DEFAULT_MAX_CLICKS;
} else {
return maxClicks;
}
}
public <F extends ObjectType> HookOperationMode click(LensContext<F> context, Task task, OperationResult result)
throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException,
ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException, PreconditionViolationException {
// DO NOT CHECK CONSISTENCY of the context here. The context may not be fresh and consistent yet. Project will fix
// that. Check consistency afterwards (and it is also checked inside projector several times).
if (context.getDebugListener() == null) {
context.setDebugListener(debugListener);
}
try {
XMLGregorianCalendar now = clock.currentTimeXMLGregorianCalendar();
// We need to determine focus before auditing. Otherwise we will not know user
// for the accounts (unless there is a specific delta for it).
// This is ugly, but it is the easiest way now (TODO: cleanup).
contextLoader.determineFocusContext((LensContext<? extends FocusType>) context, result);
ModelState state = context.getState();
if (state == ModelState.INITIAL) {
if (debugListener != null) {
debugListener.beforeSync(context);
}
metadataManager.setRequestMetadataInContext(context, now, task);
context.getStats().setRequestTimestamp(now);
// We need to do this BEFORE projection. If we would do that after projection
// there will be secondary changes that are not part of the request.
audit(context, AuditEventStage.REQUEST, task, result);
}
boolean recompute = false;
if (!context.isFresh()) {
LOGGER.trace("Context is not fresh -- forcing cleanup and recomputation");
recompute = true;
} else if (context.getExecutionWave() > context.getProjectionWave()) { // should not occur
LOGGER.warn("Execution wave is greater than projection wave -- forcing cleanup and recomputation");
recompute = true;
} else if (state == ModelState.PRIMARY && ModelExecuteOptions.getInitialPartialProcessing(context.getOptions()) != null) {
LOGGER.trace("Initial phase was run with initialPartialProcessing option -- forcing cleanup and recomputation");
recompute = true;
}
if (recompute) {
context.cleanup();
projector.project(context, "PROJECTOR ("+state+")", task, result);
} else if (context.getExecutionWave() == context.getProjectionWave()) {
LOGGER.trace("Running projector for current execution wave");
projector.resume(context, "PROJECTOR ("+state+")", task, result);
} else {
LOGGER.trace("Skipping projection because the context is fresh and projection for current wave has already run");
}
if (!context.isRequestAuthorized()) {
authorizeContextRequest(context, task, result);
}
LensUtil.traceContext(LOGGER, "CLOCKWORK (" + state + ")", "before processing", true, context, false);
if (InternalsConfig.consistencyChecks) {
try {
context.checkConsistence();
} catch (IllegalStateException e) {
throw new IllegalStateException(e.getMessage()+" in clockwork, state="+state, e);
}
}
if (InternalsConfig.encryptionChecks && !ModelExecuteOptions.isNoCrypt(context.getOptions())) {
context.checkEncrypted();
}
// LOGGER.info("CLOCKWORK: {}: {}", state, context);
switch (state) {
case INITIAL:
processInitialToPrimary(context, task, result);
break;
case PRIMARY:
processPrimaryToSecondary(context, task, result);
break;
case SECONDARY:
processSecondary(context, task, result);
break;
case FINAL:
HookOperationMode mode = processFinal(context, task, result);
if (debugListener != null) {
debugListener.afterSync(context);
}
return mode;
}
result.recomputeStatus();
result.cleanupResult();
return invokeHooks(context, task, result);
} catch (CommunicationException | ConfigurationException | ExpressionEvaluationException | ObjectNotFoundException |
PolicyViolationException | SchemaException | SecurityViolationException | RuntimeException |
ObjectAlreadyExistsException | PreconditionViolationException e) {
processClockworkException(context, e, task, result);
throw e;
}
}
/**
* Invokes hooks, if there are any.
*
* @return
* - ERROR, if any hook reported error; otherwise returns
* - BACKGROUND, if any hook reported switching to background; otherwise
* - FOREGROUND (if all hooks reported finishing on foreground)
*/
private HookOperationMode invokeHooks(LensContext context, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException {
// TODO: following two parts should be merged together in later versions
// Execute configured scripting hooks
PrismObject<SystemConfigurationType> systemConfiguration = systemObjectCache.getSystemConfiguration(result);
// systemConfiguration may be null in some tests
if (systemConfiguration != null) {
ModelHooksType modelHooks = systemConfiguration.asObjectable().getModelHooks();
if (modelHooks != null) {
HookListType changeHooks = modelHooks.getChange();
if (changeHooks != null) {
for (HookType hookType: changeHooks.getHook()) {
String shortDesc;
if (hookType.getName() != null) {
shortDesc = "hook '"+hookType.getName()+"'";
} else {
shortDesc = "scripting hook in system configuration";
}
if (hookType.isEnabled() != null && !hookType.isEnabled()) {
// Disabled hook, skip
continue;
}
if (hookType.getState() != null) {
if (!context.getState().toModelStateType().equals(hookType.getState())) {
continue;
}
}
if (hookType.getFocusType() != null) {
if (context.getFocusContext() == null) {
continue;
}
QName hookFocusTypeQname = hookType.getFocusType();
ObjectTypes hookFocusType = ObjectTypes.getObjectTypeFromTypeQName(hookFocusTypeQname);
if (hookFocusType == null) {
throw new SchemaException("Unknown focus type QName "+hookFocusTypeQname+" in "+shortDesc);
}
Class focusClass = context.getFocusClass();
Class<? extends ObjectType> hookFocusClass = hookFocusType.getClassDefinition();
if (!hookFocusClass.isAssignableFrom(focusClass)) {
continue;
}
}
ScriptExpressionEvaluatorType scriptExpressionEvaluatorType = hookType.getScript();
if (scriptExpressionEvaluatorType == null) {
continue;
}
try {
evaluateScriptingHook(context, hookType, scriptExpressionEvaluatorType, shortDesc, task, result);
} catch (ExpressionEvaluationException e) {
LOGGER.error("Evaluation of {} failed: {}", shortDesc, e.getMessage(), e);
throw new ExpressionEvaluationException("Evaluation of "+shortDesc+" failed: "+e.getMessage(), e);
} catch (ObjectNotFoundException e) {
LOGGER.error("Evaluation of {} failed: {}", shortDesc, e.getMessage(), e);
throw new ObjectNotFoundException("Evaluation of "+shortDesc+" failed: "+e.getMessage(), e);
} catch (SchemaException e) {
LOGGER.error("Evaluation of {} failed: {}", shortDesc, e.getMessage(), e);
throw new SchemaException("Evaluation of "+shortDesc+" failed: "+e.getMessage(), e);
}
}
}
}
}
// Execute registered Java hooks
HookOperationMode resultMode = HookOperationMode.FOREGROUND;
if (hookRegistry != null) {
for (ChangeHook hook : hookRegistry.getAllChangeHooks()) {
HookOperationMode mode = hook.invoke(context, task, result);
if (mode == HookOperationMode.ERROR) {
resultMode = HookOperationMode.ERROR;
} else if (mode == HookOperationMode.BACKGROUND) {
if (resultMode != HookOperationMode.ERROR) {
resultMode = HookOperationMode.BACKGROUND;
}
}
}
}
return resultMode;
}
private void evaluateScriptingHook(LensContext context, HookType hookType,
ScriptExpressionEvaluatorType scriptExpressionEvaluatorType, String shortDesc, Task task, OperationResult result)
throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
LOGGER.trace("Evaluating {}", shortDesc);
// TODO: it would be nice to cache this
// null output definition: this script has no output
ScriptExpression scriptExpression = scriptExpressionFactory.createScriptExpression(scriptExpressionEvaluatorType, null, expressionFactory, shortDesc, task, result);
ExpressionVariables variables = new ExpressionVariables();
variables.addVariableDefinition(ExpressionConstants.VAR_PRISM_CONTEXT, prismContext);
variables.addVariableDefinition(ExpressionConstants.VAR_MODEL_CONTEXT, context);
LensFocusContext focusContext = context.getFocusContext();
PrismObject focus = null;
if (focusContext != null) {
focus = focusContext.getObjectAny();
}
variables.addVariableDefinition(ExpressionConstants.VAR_FOCUS, focus);
Utils.evaluateScript(scriptExpression, context, variables, false, shortDesc, task, result);
LOGGER.trace("Finished evaluation of {}", shortDesc);
}
private <F extends ObjectType> void processInitialToPrimary(LensContext<F> context, Task task, OperationResult result) {
// Context loaded, nothing special do. Bump state to PRIMARY.
context.setState(ModelState.PRIMARY);
}
private <F extends ObjectType> void processPrimaryToSecondary(LensContext<F> context, Task task, OperationResult result) {
// Nothing to do now. The context is already recomputed.
context.setState(ModelState.SECONDARY);
}
private <F extends ObjectType> void processSecondary(LensContext<F> context, Task task, OperationResult result)
throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException, PolicyViolationException, PreconditionViolationException {
if (context.getExecutionWave() > context.getMaxWave() + 1) {
context.setState(ModelState.FINAL);
return;
}
Holder<Boolean> restartRequestedHolder = new Holder<>();
LensUtil.partialExecute("execution",
() -> {
boolean restartRequested = changeExecutor.executeChanges(context, task, result);
restartRequestedHolder.setValue(restartRequested);
},
context.getPartialProcessingOptions()::getExecution);
audit(context, AuditEventStage.EXECUTION, task, result);
rotContextIfNeeded(context);
boolean restartRequested = false;
if (restartRequestedHolder.getValue() != null) {
restartRequested = restartRequestedHolder.getValue();
}
if (!restartRequested) {
// TODO what if restart is requested indefinitely?
context.incrementExecutionWave();
} else {
// explicitly rot context?
}
LensUtil.traceContext(LOGGER, "CLOCKWORK (" + context.getState() + ")", "change execution", false, context, false);
}
/**
* Force recompute for the next execution wave. Recompute only those contexts that were changed.
* This is more intelligent than context.rot()
*/
private <F extends ObjectType> void rotContextIfNeeded(LensContext<F> context) throws SchemaException {
boolean rot = false;
for (LensProjectionContext projectionContext: context.getProjectionContexts()) {
if (projectionContext.getWave() != context.getExecutionWave()) {
LOGGER.trace("Context rot: projection {} NOT rotten because of wrong wave number", projectionContext);
continue;
}
// if (!projectionContext.isDoReconciliation()) { // meaning volatility is NONE
// LOGGER.trace("Context rot: projection {} NOT rotten because the resource is non-volatile", projectionContext);
// continue;
// }
ObjectDelta<ShadowType> execDelta = projectionContext.getExecutableDelta();
if (isShadowDeltaSignificant(execDelta)) {
LOGGER.debug("Context rot: projection {} rotten because of executable delta {}", projectionContext, execDelta);
projectionContext.setFresh(false);
projectionContext.setFullShadow(false);
rot = true;
// Propagate to higher-order projections
for (LensProjectionContext relCtx: LensUtil.findRelatedContexts(context, projectionContext)) {
relCtx.setFresh(false);
relCtx.setFullShadow(false);
}
} else {
LOGGER.trace("Context rot: projection {} NOT rotten because no delta", projectionContext);
}
}
LensFocusContext<F> focusContext = context.getFocusContext();
if (focusContext != null) {
ObjectDelta<F> execDelta = focusContext.getWaveDelta(context.getExecutionWave());
if (execDelta != null && !execDelta.isEmpty()) {
LOGGER.debug("Context rot: context rotten because of focus execution delta {}", execDelta);
rot = true;
}
if (rot) {
// It is OK to refresh focus all the time there was any change. This is cheap.
focusContext.setFresh(false);
}
//remove secondary deltas from other than execution wave - we need to recompute them..
// cleanUpSecondaryDeltas(context);
}
if (rot) {
context.setFresh(false);
}
}
// // TODO this is quite unclear. Originally here was keeping the delta from the current wave (plus delta from wave #1).
// // The reason was not clear.
// // Let us erase everything.
// private <F extends ObjectType> void cleanUpSecondaryDeltas(LensContext<F> context){
// LensFocusContext focusContext = context.getFocusContext();
// ObjectDeltaWaves<F> executionWaveDeltaList = focusContext.getSecondaryDeltas();
// executionWaveDeltaList.clear();
// }
private <P extends ObjectType> boolean isShadowDeltaSignificant(ObjectDelta<P> delta) {
if (delta == null || delta.isEmpty()) {
return false;
}
if (delta.isAdd() || delta.isDelete()) {
return true;
}
Collection<? extends ItemDelta<?,?>> attrDeltas = delta.findItemDeltasSubPath(new ItemPath(ShadowType.F_ATTRIBUTES));
if (attrDeltas != null && !attrDeltas.isEmpty()) {
return true;
}
return false;
}
private <F extends ObjectType> HookOperationMode processFinal(LensContext<F> context, Task task, OperationResult result)
throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException, PolicyViolationException, PreconditionViolationException {
auditFinalExecution(context, task, result);
logFinalReadable(context, task, result);
recordOperationExecution(context, null, task, result);
migrator.executeAfterOperationMigration(context, result);
HookOperationMode opmode = personaProcessor.processPersonaChanges(context, task, result);
if (opmode == HookOperationMode.BACKGROUND) {
return opmode;
}
return triggerReconcileAffected(context, task, result);
}
private <F extends ObjectType> void recordOperationExecution(LensContext<F> context, Throwable clockworkException,
Task task, OperationResult result)
throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException {
XMLGregorianCalendar now = clock.currentTimeXMLGregorianCalendar();
try {
LOGGER.trace("recordOperationExecution starting; task = {}, clockworkException = {}", task, clockworkException);
recordFocusOperationExecution(context, now, clockworkException, task, result);
for (LensProjectionContext projectionContext : context.getProjectionContexts()) {
recordProjectionOperationExecution(context, projectionContext, now, task, result);
}
} catch (Throwable t) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't record operation execution. Model context:\n{}", t, context.debugDump());
// Let us ignore this for the moment. It should not have happened, sure. But it's not that crucial.
// Administrator will be able to learn about the problem from the log.
}
}
private <F extends ObjectType> void recordFocusOperationExecution(LensContext<F> context, XMLGregorianCalendar now,
Throwable clockworkException, Task task, OperationResult result)
throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException {
LensFocusContext<F> focusContext = context.getFocusContext();
if (focusContext == null || focusContext.isDelete()) {
LOGGER.trace("focusContext is null or 'delete', not recording focus operation execution");
return;
}
PrismObject<F> objectNew = focusContext.getObjectNew();
Validate.notNull(objectNew, "No focus object even if the context is not of 'delete' type");
List<LensObjectDeltaOperation<F>> executedDeltas;
if (clockworkException == null) {
executedDeltas = focusContext.getExecutedDeltas();
} else {
executedDeltas = new ArrayList<>(focusContext.getExecutedDeltas());
LensObjectDeltaOperation<F> odo = new LensObjectDeltaOperation<>();
ObjectDelta<F> primaryDelta = focusContext.getPrimaryDelta();
if (primaryDelta != null) {
odo.setObjectDelta(primaryDelta);
} else {
@SuppressWarnings({"unchecked", "raw"})
Class<F> fClass = (Class<F>) objectNew.asObjectable().getClass();
ObjectDelta<F> fakeDelta = new ObjectDelta<>(fClass, ChangeType.MODIFY, prismContext);
odo.setObjectDelta(fakeDelta);
}
odo.setExecutionResult(result); // we rely on the fact that 'result' already contains record of the exception
executedDeltas.add(odo);
}
LOGGER.trace("recordFocusOperationExecution: executedDeltas: {}", executedDeltas.size());
recordOperationExecution(objectNew, false, executedDeltas, now, context.getChannel(), task, result);
}
private <F extends ObjectType> void recordProjectionOperationExecution(LensContext<F> context,
LensProjectionContext projectionContext, XMLGregorianCalendar now, Task task, OperationResult result)
throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException {
PrismObject<ShadowType> object = projectionContext.getObjectAny();
if (object == null) {
return; // this can happen
}
recordOperationExecution(object, true, projectionContext.getExecutedDeltas(), now,
context.getChannel(), task, result);
}
private <F extends ObjectType> void recordOperationExecution(PrismObject<F> object, boolean deletedOk,
List<LensObjectDeltaOperation<F>> executedDeltas, XMLGregorianCalendar now,
String channel, Task task, OperationResult result)
throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException {
OperationExecutionType operation = new OperationExecutionType(prismContext);
OperationResult summaryResult = new OperationResult("dummy");
String oid = object.getOid();
for (LensObjectDeltaOperation<F> deltaOperation : executedDeltas) {
operation.getOperation().add(createObjectDeltaOperation(deltaOperation));
if (deltaOperation.getExecutionResult() != null) {
summaryResult.addSubresult(deltaOperation.getExecutionResult());
}
if (oid == null && deltaOperation.getObjectDelta() != null) {
oid = deltaOperation.getObjectDelta().getOid();
}
}
if (oid == null) { // e.g. if there is an exception in provisioning.addObject method
LOGGER.trace("recordOperationExecution: skipping because oid is null for object = {}", object);
return;
}
summaryResult.computeStatus();
OperationResultStatusType overallStatus = summaryResult.getStatus().createStatusType();
setOperationContext(operation, overallStatus, now, channel, task);
storeOperationExecution(object, oid, operation, deletedOk, result);
}
private <F extends ObjectType> void storeOperationExecution(@NotNull PrismObject<F> object, @NotNull String oid,
@NotNull OperationExecutionType executionToAdd, boolean deletedOk, OperationResult result)
throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException {
Integer recordsToKeep;
Long deleteBefore;
boolean keepNoExecutions = false;
PrismObject<SystemConfigurationType> systemConfiguration = systemObjectCache.getSystemConfiguration(result);
if (systemConfiguration != null && systemConfiguration.asObjectable().getCleanupPolicy() != null
&& systemConfiguration.asObjectable().getCleanupPolicy().getObjectResults() != null) {
CleanupPolicyType policy = systemConfiguration.asObjectable().getCleanupPolicy().getObjectResults();
recordsToKeep = policy.getMaxRecords();
if (recordsToKeep != null && recordsToKeep == 0) {
LOGGER.trace("objectResults.recordsToKeep is 0, will skip storing operationExecutions");
keepNoExecutions = true;
}
if (policy.getMaxAge() != null) {
XMLGregorianCalendar limit = XmlTypeConverter.addDuration(
XmlTypeConverter.createXMLGregorianCalendar(new Date()), policy.getMaxAge().negate());
deleteBefore = XmlTypeConverter.toMillis(limit);
} else {
deleteBefore = null;
}
} else {
recordsToKeep = DEFAULT_NUMBER_OF_RESULTS_TO_KEEP;
deleteBefore = null;
}
List<OperationExecutionType> executionsToDelete = new ArrayList<>();
List<OperationExecutionType> executions = new ArrayList<>(object.asObjectable().getOperationExecution());
// delete all executions related to current task and all old ones
String taskOid = executionToAdd.getTaskRef() != null ? executionToAdd.getTaskRef().getOid() : null;
for (Iterator<OperationExecutionType> iterator = executions.iterator(); iterator.hasNext(); ) {
OperationExecutionType execution = iterator.next();
if (taskOid != null && execution.getTaskRef() != null && taskOid.equals(execution.getTaskRef().getOid())
|| deleteBefore != null && XmlTypeConverter.toMillis(execution.getTimestamp()) < deleteBefore) {
executionsToDelete.add(execution);
iterator.remove();
}
}
// delete all surplus executions
if (recordsToKeep != null && executions.size() > recordsToKeep - 1) {
if (keepNoExecutions) {
executionsToDelete.addAll(executions);
} else {
executions.sort(Comparator.nullsFirst(Comparator.comparing(e -> XmlTypeConverter.toDate(e.getTimestamp()))));
executionsToDelete.addAll(executions.subList(0, executions.size() - (recordsToKeep - 1)));
}
}
// construct and execute the delta
Class<? extends ObjectType> objectClass = object.asObjectable().getClass();
List<ItemDelta<?, ?>> deltas = new ArrayList<>();
if (!keepNoExecutions) {
deltas.add(DeltaBuilder.deltaFor(objectClass, prismContext)
.item(ObjectType.F_OPERATION_EXECUTION)
.add(executionToAdd)
.asItemDelta());
}
if (!executionsToDelete.isEmpty()) {
deltas.add(DeltaBuilder.deltaFor(objectClass, prismContext)
.item(ObjectType.F_OPERATION_EXECUTION)
.delete(PrismContainerValue.toPcvList(CloneUtil.cloneCollectionMembers(executionsToDelete)))
.asItemDelta());
}
LOGGER.trace("Operation execution delta:\n{}", DebugUtil.debugDumpLazily(deltas));
try {
if (!deltas.isEmpty()) {
repositoryService.modifyObject(objectClass, oid, deltas, result);
}
} catch (ObjectNotFoundException e) {
if (!deletedOk) {
throw e;
} else {
LOGGER.trace("Object {} deleted but this was expected.", oid);
result.deleteLastSubresultIfError();
}
}
}
private void setOperationContext(OperationExecutionType operation,
OperationResultStatusType overallStatus, XMLGregorianCalendar now, String channel, Task task) {
if (task.getParentForLightweightAsynchronousTask() != null) {
task = task.getParentForLightweightAsynchronousTask();
}
if (task.isPersistent()) {
operation.setTaskRef(ObjectTypeUtil.createObjectRef(task.getTaskPrismObject()));
}
operation.setStatus(overallStatus);
operation.setInitiatorRef(ObjectTypeUtil.createObjectRef(task.getOwner())); // TODO what if the real initiator is different? (e.g. when executing approved changes)
operation.setChannel(channel);
operation.setTimestamp(now);
}
private <F extends ObjectType> ObjectDeltaOperationType createObjectDeltaOperation(LensObjectDeltaOperation<F> deltaOperation) {
ObjectDeltaOperationType odo;
try {
odo = simplifyOperation(deltaOperation).toLensObjectDeltaOperationType().getObjectDeltaOperation();
} catch (SchemaException e) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't create operation information", e);
odo = new ObjectDeltaOperationType();
OperationResult r = new OperationResult(Clockwork.class.getName() + ".createObjectDeltaOperation");
r.recordFatalError("Couldn't create operation information: " + e.getMessage(), e);
odo.setExecutionResult(r.createOperationResultType());
}
return odo;
}
private <F extends ObjectType> LensObjectDeltaOperation<F> simplifyOperation(ObjectDeltaOperation<F> operation) {
LensObjectDeltaOperation<F> rv = new LensObjectDeltaOperation<>();
rv.setObjectDelta(simplifyDelta(operation.getObjectDelta()));
rv.setExecutionResult(OperationResult.keepRootOnly(operation.getExecutionResult()));
rv.setObjectName(operation.getObjectName());
rv.setResourceName(operation.getResourceName());
rv.setResourceOid(operation.getResourceOid());
return rv;
}
private <F extends ObjectType> ObjectDelta<F> simplifyDelta(ObjectDelta<F> delta) {
return new ObjectDelta<>(delta.getObjectTypeClass(), delta.getChangeType(), prismContext);
}
private <F extends ObjectType> HookOperationMode triggerReconcileAffected(LensContext<F> context, Task task, OperationResult result) throws SchemaException {
// check applicability
if (!ModelExecuteOptions.isReconcileAffected(context.getOptions())) {
return HookOperationMode.FOREGROUND;
}
if (context.getFocusClass() == null || !RoleType.class.isAssignableFrom(context.getFocusClass())) {
LOGGER.warn("ReconcileAffected requested but not available for {}. Doing nothing.", context.getFocusClass());
return HookOperationMode.FOREGROUND;
}
// check preconditions
if (context.getFocusContext() == null) {
throw new IllegalStateException("No focus context when expected it");
}
PrismObject<RoleType> role = (PrismObject) context.getFocusContext().getObjectAny();
if (role == null) {
throw new IllegalStateException("No role when expected it");
}
// preparing the recompute/reconciliation task
Task reconTask;
if (task.isPersistent()) {
reconTask = task.createSubtask();
} else {
reconTask = task;
}
assert !reconTask.isPersistent();
// creating object query
PrismPropertyDefinition propertyDef = prismContext.getSchemaRegistry()
.findPropertyDefinitionByElementName(SchemaConstants.MODEL_EXTENSION_OBJECT_QUERY);
PrismReferenceValue referenceValue = new PrismReferenceValue(context.getFocusContext().getOid(), RoleType.COMPLEX_TYPE);
ObjectFilter refFilter = QueryBuilder.queryFor(FocusType.class, prismContext)
.item(FocusType.F_ASSIGNMENT, AssignmentType.F_TARGET_REF).ref(referenceValue)
.buildFilter();
SearchFilterType filterType = QueryConvertor.createSearchFilterType(refFilter, prismContext);
QueryType queryType = new QueryType();
queryType.setFilter(filterType);
PrismProperty<QueryType> property = propertyDef.instantiate();
property.setRealValue(queryType);
reconTask.addExtensionProperty(property);
// other parameters