/
ChangeExecutor.java
1609 lines (1417 loc) · 65.9 KB
/
ChangeExecutor.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 static com.evolveum.midpoint.model.api.ProgressInformation.ActivityType.FOCUS_OPERATION;
import static com.evolveum.midpoint.model.api.ProgressInformation.ActivityType.RESOURCE_OBJECT_OPERATION;
import static com.evolveum.midpoint.model.api.ProgressInformation.StateType.ENTERING;
import static com.evolveum.midpoint.schema.internals.InternalsConfig.consistencyChecks;
import com.evolveum.midpoint.common.Clock;
import com.evolveum.midpoint.common.SynchronizationUtils;
import com.evolveum.midpoint.model.impl.lens.projector.policy.PolicySituationUpdater;
import com.evolveum.midpoint.repo.api.ConflictWatcher;
import com.evolveum.midpoint.repo.common.expression.Expression;
import com.evolveum.midpoint.repo.common.expression.ExpressionEvaluationContext;
import com.evolveum.midpoint.repo.common.expression.ExpressionFactory;
import com.evolveum.midpoint.repo.common.expression.ExpressionUtil;
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.ProgressInformation;
import com.evolveum.midpoint.model.api.context.SynchronizationPolicyDecision;
import com.evolveum.midpoint.model.impl.ModelObjectResolver;
import com.evolveum.midpoint.model.impl.expr.ExpressionEnvironment;
import com.evolveum.midpoint.model.impl.expr.ModelExpressionThreadLocalHolder;
import com.evolveum.midpoint.model.impl.lens.projector.FocusConstraintsChecker;
import com.evolveum.midpoint.model.impl.lens.projector.credentials.CredentialsProcessor;
import com.evolveum.midpoint.model.impl.util.Utils;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.prism.delta.ChangeType;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple;
import com.evolveum.midpoint.prism.delta.PropertyDelta;
import com.evolveum.midpoint.prism.delta.ReferenceDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.xnode.PrimitiveXNode;
import com.evolveum.midpoint.provisioning.api.ProvisioningOperationOptions;
import com.evolveum.midpoint.provisioning.api.ProvisioningService;
import com.evolveum.midpoint.repo.api.RepoAddOptions;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.ObjectDeltaOperation;
import com.evolveum.midpoint.schema.PointInTimeType;
import com.evolveum.midpoint.schema.ResourceShadowDiscriminator;
import com.evolveum.midpoint.schema.SelectorOptions;
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.ShadowUtil;
import com.evolveum.midpoint.security.api.OwnerResolver;
import com.evolveum.midpoint.security.api.SecurityEnforcer;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskManager;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.MiscUtil;
import com.evolveum.midpoint.util.QNameUtil;
import com.evolveum.midpoint.util.exception.*;
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.RawType;
import org.apache.commons.lang.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
/**
* @author semancik
*/
@Component
public class ChangeExecutor {
private static final Trace LOGGER = TraceManager.getTrace(ChangeExecutor.class);
private static final String OPERATION_EXECUTE_DELTA = ChangeExecutor.class.getName() + ".executeDelta";
private static final String OPERATION_EXECUTE = ChangeExecutor.class.getName() + ".execute";
private static final String OPERATION_EXECUTE_FOCUS = OPERATION_EXECUTE + ".focus";
private static final String OPERATION_EXECUTE_PROJECTION = OPERATION_EXECUTE + ".projection";
private static final String OPERATION_LINK_ACCOUNT = ChangeExecutor.class.getName() + ".linkShadow";
private static final String OPERATION_UNLINK_ACCOUNT = ChangeExecutor.class.getName() + ".unlinkShadow";
private static final String OPERATION_UPDATE_SITUATION_ACCOUNT = ChangeExecutor.class.getName()
+ ".updateSituationInShadow";
@Autowired private transient TaskManager taskManager;
@Autowired @Qualifier("cacheRepositoryService") private transient RepositoryService cacheRepositoryService;
@Autowired private ProvisioningService provisioning;
@Autowired private PrismContext prismContext;
@Autowired private ExpressionFactory expressionFactory;
@Autowired private SecurityEnforcer securityEnforcer;
@Autowired private Clock clock;
@Autowired private ModelObjectResolver objectResolver;
@Autowired private OperationalDataManager metadataManager;
@Autowired private PolicySituationUpdater policySituationUpdater;
@Autowired private CredentialsProcessor credentialsProcessor;
private PrismObjectDefinition<UserType> userDefinition = null;
private PrismObjectDefinition<ShadowType> shadowDefinition = null;
@PostConstruct
private void locateDefinitions() {
userDefinition = prismContext.getSchemaRegistry()
.findObjectDefinitionByCompileTimeClass(UserType.class);
shadowDefinition = prismContext.getSchemaRegistry()
.findObjectDefinitionByCompileTimeClass(ShadowType.class);
}
// returns true if current operation has to be restarted, see
// ObjectAlreadyExistsException handling (TODO specify more exactly)
public <O extends ObjectType> boolean executeChanges(LensContext<O> context, Task task,
OperationResult parentResult) throws ObjectAlreadyExistsException, ObjectNotFoundException,
SchemaException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
OperationResult result = parentResult.createSubresult(OPERATION_EXECUTE);
// FOCUS
context.checkAbortRequested();
LensFocusContext<O> focusContext = context.getFocusContext();
if (focusContext != null) {
ObjectDelta<O> focusDelta = focusContext.getWaveExecutableDelta(context.getExecutionWave());
for (ItemDelta<?, ?> itemDelta : focusContext.getPendingPolicySituationModifications()) {
focusContext.swallowToSecondaryDelta(itemDelta);
}
focusContext.clearPendingPolicySituationModifications();
if (focusDelta != null) {
ObjectPolicyConfigurationType objectPolicyConfigurationType = focusContext
.getObjectPolicyConfigurationType();
applyObjectPolicy(focusContext, focusDelta, objectPolicyConfigurationType);
OperationResult subResult = result.createSubresult(
OPERATION_EXECUTE_FOCUS + "." + focusContext.getObjectTypeClass().getSimpleName());
try {
// Will remove credential deltas or hash them
focusDelta = credentialsProcessor.transformFocusExectionDelta(context, focusDelta);
} catch (EncryptionException e) {
recordFatalError(subResult, result, null, e);
result.computeStatus();
throw new SystemException(e.getMessage(), e);
}
try {
context.reportProgress(new ProgressInformation(FOCUS_OPERATION, ENTERING));
executeDelta(focusDelta, focusContext, context, null, null, task, subResult);
if (focusDelta.isAdd() && focusDelta.getOid() != null) {
ConflictWatcher watcher = context.createAndRegisterConflictWatcher(focusDelta.getOid(), cacheRepositoryService);
watcher.setExpectedVersion(focusDelta.getObjectToAdd().getVersion());
}
subResult.computeStatus();
} catch (SchemaException | ObjectNotFoundException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException | RuntimeException e) {
recordFatalError(subResult, result, null, e);
throw e;
} catch (ObjectAlreadyExistsException e) {
subResult.computeStatus();
if (!subResult.isSuccess() && !subResult.isHandledError()) {
subResult.recordFatalError(e);
}
result.computeStatusComposite();
throw e;
} finally {
context.reportProgress(new ProgressInformation(FOCUS_OPERATION, subResult));
}
} else {
LOGGER.trace("Skipping focus change execute, because user delta is null");
}
}
// PROJECTIONS
context.checkAbortRequested();
boolean restartRequested = false;
for (LensProjectionContext projCtx : context.getProjectionContexts()) {
if (projCtx.getWave() != context.getExecutionWave()) {
continue;
}
if (!projCtx.isCanProject()) {
continue;
}
// we should not get here, but just to be sure
if (projCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.IGNORE) {
LOGGER.trace("Skipping ignored projection context {}", projCtx.toHumanReadableString());
continue;
}
OperationResult subResult = result.createSubresult(
OPERATION_EXECUTE_PROJECTION + "." + projCtx.getObjectTypeClass().getSimpleName());
subResult.addArbitraryObjectAsContext("discriminator", projCtx.getResourceShadowDiscriminator());
if (projCtx.getResource() != null) {
subResult.addParam("resource", projCtx.getResource());
}
try {
context.checkAbortRequested();
context.reportProgress(new ProgressInformation(RESOURCE_OBJECT_OPERATION,
projCtx.getResourceShadowDiscriminator(), ENTERING));
executeReconciliationScript(projCtx, context, BeforeAfterType.BEFORE, task, subResult);
ObjectDelta<ShadowType> projDelta = projCtx.getExecutableDelta();
if (shouldBeDeleted(projDelta, projCtx)) {
projDelta = ObjectDelta.createDeleteDelta(projCtx.getObjectTypeClass(), projCtx.getOid(),
prismContext);
}
if (projCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.BROKEN) {
if (context.getFocusContext() != null
&& context.getFocusContext().getDelta() != null
&& context.getFocusContext().getDelta().isDelete()
&& context.getOptions() != null
&& ModelExecuteOptions.isForce(context.getOptions())) {
if (projDelta == null) {
projDelta = ObjectDelta.createDeleteDelta(projCtx.getObjectTypeClass(),
projCtx.getOid(), prismContext);
}
}
if (projDelta != null && projDelta.isDelete()) {
executeDelta(projDelta, projCtx, context, null, projCtx.getResource(), task,
subResult);
}
} else {
if (projDelta == null || projDelta.isEmpty()) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("No change for " + projCtx.getResourceShadowDiscriminator());
}
if (focusContext != null) {
updateLinks(focusContext, projCtx, task, subResult);
}
// Make sure post-reconcile delta is always executed,
// even if there is no change
executeReconciliationScript(projCtx, context, BeforeAfterType.AFTER, task,
subResult);
subResult.computeStatus();
subResult.recordNotApplicableIfUnknown();
continue;
} else if (projDelta.isDelete() && projCtx.getResourceShadowDiscriminator() != null
&& projCtx.getResourceShadowDiscriminator().getOrder() > 0) {
// HACK ... for higher-order context check if this was
// already deleted
LensProjectionContext lowerOrderContext = LensUtil.findLowerOrderContext(context,
projCtx);
if (lowerOrderContext != null && lowerOrderContext.isDelete()) {
// We assume that this was already executed
subResult.setStatus(OperationResultStatus.NOT_APPLICABLE);
continue;
}
}
executeDelta(projDelta, projCtx, context, null, projCtx.getResource(), task, subResult);
}
subResult.computeStatus();
if (focusContext != null) {
updateLinks(focusContext, projCtx, task, subResult);
}
executeReconciliationScript(projCtx, context, BeforeAfterType.AFTER, task, subResult);
subResult.computeStatus();
subResult.recordNotApplicableIfUnknown();
} catch (SchemaException e) {
recordProjectionExecutionException(e, projCtx, subResult,
SynchronizationPolicyDecision.BROKEN);
continue;
} catch (ObjectNotFoundException e) {
recordProjectionExecutionException(e, projCtx, subResult,
SynchronizationPolicyDecision.BROKEN);
continue;
} catch (ObjectAlreadyExistsException e) {
// check if this is a repeated attempt - OAEE was not handled
// correctly, e.g. if creating "Users" user in AD, whereas
// "Users" is SAM Account Name which is used by a built-in group
// - in such case, mark the context as broken
if (isRepeatedAlreadyExistsException(projCtx)) {
recordProjectionExecutionException(e, projCtx, subResult,
SynchronizationPolicyDecision.BROKEN);
continue;
}
// in his case we do not need to set account context as
// broken, instead we need to restart projector for this
// context to recompute new account or find out if the
// account was already linked..
// and also do not set fatal error to the operation result, this
// is a special case
// if it is fatal, it will be set later
// but we need to set some result
subResult.recordSuccess();
subResult.muteLastSubresultError();
restartRequested = true;
break; // we will process remaining projections when retrying
// the wave
} catch (CommunicationException e) {
recordProjectionExecutionException(e, projCtx, subResult,
SynchronizationPolicyDecision.BROKEN);
continue;
} catch (ConfigurationException e) {
recordProjectionExecutionException(e, projCtx, subResult,
SynchronizationPolicyDecision.BROKEN);
continue;
} catch (SecurityViolationException e) {
recordProjectionExecutionException(e, projCtx, subResult,
SynchronizationPolicyDecision.BROKEN);
continue;
} catch (ExpressionEvaluationException e) {
recordProjectionExecutionException(e, projCtx, subResult,
SynchronizationPolicyDecision.BROKEN);
continue;
} catch (RuntimeException e) {
recordProjectionExecutionException(e, projCtx, subResult,
SynchronizationPolicyDecision.BROKEN);
continue;
} finally {
context.reportProgress(new ProgressInformation(RESOURCE_OBJECT_OPERATION,
projCtx.getResourceShadowDiscriminator(), subResult));
}
}
// Result computation here needs to be slightly different
result.computeStatusComposite();
return restartRequested;
}
private boolean shouldBeDeleted(ObjectDelta<ShadowType> accDelta, LensProjectionContext accCtx) {
return (accDelta == null || accDelta.isEmpty())
&& (accCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.DELETE
|| accCtx.getSynchronizationIntent() == SynchronizationIntent.DELETE);
}
private <O extends ObjectType> boolean isRepeatedAlreadyExistsException(
LensProjectionContext projContext) {
int deltas = projContext.getExecutedDeltas().size();
LOGGER.trace("isRepeatedAlreadyExistsException starting; number of executed deltas = {}", deltas);
if (deltas < 2) {
return false;
}
LensObjectDeltaOperation<ShadowType> lastDeltaOp = projContext.getExecutedDeltas().get(deltas - 1);
LensObjectDeltaOperation<ShadowType> previousDeltaOp = projContext.getExecutedDeltas()
.get(deltas - 2);
// TODO check also previous execution result to see if it's
// AlreadyExistException?
ObjectDelta<ShadowType> lastDelta = lastDeltaOp.getObjectDelta();
ObjectDelta<ShadowType> previousDelta = previousDeltaOp.getObjectDelta();
boolean rv;
if (lastDelta.isAdd() && previousDelta.isAdd()) {
rv = isEquivalentAddDelta(lastDelta.getObjectToAdd(), previousDelta.getObjectToAdd());
} else if (lastDelta.isModify() && previousDelta.isModify()) {
rv = isEquivalentModifyDelta(lastDelta.getModifications(), previousDelta.getModifications());
} else {
rv = false;
}
LOGGER.trace(
"isRepeatedAlreadyExistsException returning {}; based of comparison of previousDelta:\n{}\nwith lastDelta:\n{}",
rv, previousDelta, lastDelta);
return rv;
}
private boolean isEquivalentModifyDelta(Collection<? extends ItemDelta<?, ?>> modifications1,
Collection<? extends ItemDelta<?, ?>> modifications2) {
Collection<? extends ItemDelta<?, ?>> attrDeltas1 = ItemDelta.findItemDeltasSubPath(modifications1,
new ItemPath(ShadowType.F_ATTRIBUTES));
Collection<? extends ItemDelta<?, ?>> attrDeltas2 = ItemDelta.findItemDeltasSubPath(modifications2,
new ItemPath(ShadowType.F_ATTRIBUTES));
return MiscUtil.unorderedCollectionEquals(attrDeltas1, attrDeltas2);
}
private boolean isEquivalentAddDelta(PrismObject<ShadowType> object1, PrismObject<ShadowType> object2) {
PrismContainer attributes1 = object1.findContainer(ShadowType.F_ATTRIBUTES);
PrismContainer attributes2 = object2.findContainer(ShadowType.F_ATTRIBUTES);
if (attributes1 == null || attributes2 == null || attributes1.size() != 1
|| attributes2.size() != 1) { // suspicious cases
return false;
}
return attributes1.getValue().equivalent(attributes2.getValue());
}
private <O extends ObjectType> void applyObjectPolicy(LensFocusContext<O> focusContext,
ObjectDelta<O> focusDelta, ObjectPolicyConfigurationType objectPolicyConfigurationType) {
if (objectPolicyConfigurationType == null) {
return;
}
PrismObject<O> objectNew = focusContext.getObjectNew();
if (focusDelta.isAdd() && objectNew.getOid() == null) {
for (PropertyConstraintType propertyConstraintType : objectPolicyConfigurationType
.getPropertyConstraint()) {
if (BooleanUtils.isTrue(propertyConstraintType.isOidBound())) {
ItemPath itemPath = propertyConstraintType.getPath().getItemPath();
PrismProperty<Object> prop = objectNew.findProperty(itemPath);
String stringValue = prop.getRealValue().toString();
focusContext.setOid(stringValue);
}
}
// deprecated
if (BooleanUtils.isTrue(objectPolicyConfigurationType.isOidNameBoundMode())) {
String name = objectNew.asObjectable().getName().getOrig();
focusContext.setOid(name);
}
}
}
private <P extends ObjectType> void recordProjectionExecutionException(Exception e,
LensProjectionContext accCtx, OperationResult subResult, SynchronizationPolicyDecision decision) {
subResult.recordFatalError(e);
LOGGER.error("Error executing changes for {}: {}",
new Object[] { accCtx.toHumanReadableString(), e.getMessage(), e });
if (decision != null) {
accCtx.setSynchronizationPolicyDecision(decision);
}
}
private void recordFatalError(OperationResult subResult, OperationResult result, String message,
Throwable e) {
if (message == null) {
message = e.getMessage();
}
subResult.recordFatalError(e);
if (result != null) {
result.computeStatusComposite();
}
}
/**
* Make sure that the account is linked (or unlinked) as needed.
*/
private <O extends ObjectType, F extends FocusType> void updateLinks(
LensFocusContext<O> focusObjectContext, LensProjectionContext projCtx, Task task,
OperationResult result) throws ObjectNotFoundException, SchemaException {
if (focusObjectContext == null) {
return;
}
Class<O> objectTypeClass = focusObjectContext.getObjectTypeClass();
if (!FocusType.class.isAssignableFrom(objectTypeClass)) {
return;
}
LensFocusContext<F> focusContext = (LensFocusContext<F>) focusObjectContext;
if (projCtx.getResourceShadowDiscriminator() != null
&& projCtx.getResourceShadowDiscriminator().getOrder() > 0) {
// Don't mess with links for higher-order contexts. The link should
// be dealt with
// during processing of zero-order context.
return;
}
String projOid = projCtx.getOid();
if (projOid == null) {
if (projCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.BROKEN) {
// This seems to be OK. In quite a strange way, but still OK.
return;
}
LOGGER.trace("Shadow has null OID, this should not happen, context:\n{}", projCtx.debugDump());
throw new IllegalStateException("Shadow has null OID, this should not happen");
}
if (linkShouldExist(projCtx, result)) {
// Link should exist
PrismObject<F> objectCurrent = focusContext.getObjectCurrent();
if (objectCurrent != null) {
for (ObjectReferenceType linkRef : objectCurrent.asObjectable().getLinkRef()) {
if (projOid.equals(linkRef.getOid())) {
// Already linked, nothing to do, only be sure, the
// situation is set with the good value
LOGGER.trace("Updating situation in already linked shadow.");
updateSituationInShadow(task, SynchronizationSituationType.LINKED, focusObjectContext,
projCtx, result);
return;
}
}
}
// Not linked, need to link
linkShadow(focusContext.getOid(), projOid, focusObjectContext, projCtx, task, result);
// be sure, that the situation is set correctly
LOGGER.trace("Updating situation after shadow was linked.");
updateSituationInShadow(task, SynchronizationSituationType.LINKED, focusObjectContext, projCtx,
result);
} else {
// Link should NOT exist
if (!focusContext.isDelete()) {
PrismObject<F> objectCurrent = focusContext.getObjectCurrent();
// it is possible that objectCurrent is null (and objectNew is
// non-null), in case of User ADD operation (MID-2176)
if (objectCurrent != null) {
PrismReference linkRef = objectCurrent.findReference(FocusType.F_LINK_REF);
if (linkRef != null) {
for (PrismReferenceValue linkRefVal : linkRef.getValues()) {
if (linkRefVal.getOid().equals(projOid)) {
// Linked, need to unlink
unlinkShadow(focusContext.getOid(), linkRefVal, focusObjectContext, projCtx,
task, result);
}
}
}
}
}
if (projCtx.isDelete() || projCtx.isThombstone()) {
LOGGER.trace("Resource object {} deleted, updating also situation in shadow.", projOid);
// HACK HACK?
try {
updateSituationInShadow(task, SynchronizationSituationType.DELETED, focusObjectContext,
projCtx, result);
} catch (ObjectNotFoundException e) {
// HACK HACK?
LOGGER.trace(
"Resource object {} is gone, cannot update situation in shadow (this is probably harmless).",
projOid);
result.getLastSubresult().setStatus(OperationResultStatus.HANDLED_ERROR);
}
} else {
// This should NOT be UNLINKED. We just do not know the
// situation here. Reflect that in the shadow.
LOGGER.trace("Resource object {} unlinked from the user, updating also situation in shadow.",
projOid);
updateSituationInShadow(task, null, focusObjectContext, projCtx, result);
}
// Not linked, that's OK
}
}
private boolean linkShouldExist(LensProjectionContext projCtx, OperationResult result) {
if (projCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.UNLINK) {
return false;
}
if (isEmptyThombstone(projCtx)) {
return false;
}
if (projCtx.hasPendingOperations()) {
return true;
}
if (projCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.DELETE
|| projCtx.isDelete()) {
if (result.isInProgress()) {
// Keep the link until operation is finished
return true;
} else {
return false;
}
}
return true;
}
/**
* Return true if this projection is just a linkRef that points to no
* shadow.
*/
private boolean isEmptyThombstone(LensProjectionContext projCtx) {
return projCtx.getResourceShadowDiscriminator() != null
&& projCtx.getResourceShadowDiscriminator().isThombstone()
&& projCtx.getObjectCurrent() == null;
}
private <F extends ObjectType> void linkShadow(String userOid, String shadowOid,
LensElementContext<F> focusContext, LensProjectionContext projCtx, Task task,
OperationResult parentResult) throws ObjectNotFoundException, SchemaException {
Class<F> typeClass = focusContext.getObjectTypeClass();
if (!FocusType.class.isAssignableFrom(typeClass)) {
return;
}
String channel = focusContext.getLensContext().getChannel();
LOGGER.debug("Linking shadow " + shadowOid + " to focus " + userOid);
OperationResult result = parentResult.createSubresult(OPERATION_LINK_ACCOUNT);
PrismReferenceValue linkRef = new PrismReferenceValue();
linkRef.setOid(shadowOid);
linkRef.setTargetType(ShadowType.COMPLEX_TYPE);
Collection<? extends ItemDelta> linkRefDeltas = ReferenceDelta
.createModificationAddCollection(FocusType.F_LINK_REF, getUserDefinition(), linkRef);
try {
cacheRepositoryService.modifyObject(typeClass, userOid, linkRefDeltas, result);
task.recordObjectActionExecuted(focusContext.getObjectAny(), typeClass, userOid,
ChangeType.MODIFY, channel, null);
} catch (ObjectAlreadyExistsException ex) {
task.recordObjectActionExecuted(focusContext.getObjectAny(), typeClass, userOid,
ChangeType.MODIFY, channel, ex);
throw new SystemException(ex);
} catch (Throwable t) {
task.recordObjectActionExecuted(focusContext.getObjectAny(), typeClass, userOid,
ChangeType.MODIFY, channel, t);
throw t;
} finally {
result.computeStatus();
ObjectDelta<F> userDelta = ObjectDelta.createModifyDelta(userOid, linkRefDeltas, typeClass,
prismContext);
LensObjectDeltaOperation<F> userDeltaOp = LensUtil.createObjectDeltaOperation(userDelta, result,
focusContext, projCtx);
focusContext.addToExecutedDeltas(userDeltaOp);
}
}
private PrismObjectDefinition<UserType> getUserDefinition() {
return userDefinition;
}
private <F extends ObjectType> void unlinkShadow(String focusOid, PrismReferenceValue accountRef,
LensElementContext<F> focusContext, LensProjectionContext projCtx, Task task,
OperationResult parentResult) throws ObjectNotFoundException, SchemaException {
Class<F> typeClass = focusContext.getObjectTypeClass();
if (!FocusType.class.isAssignableFrom(typeClass)) {
return;
}
String channel = focusContext.getLensContext().getChannel();
LOGGER.debug("Unlinking shadow " + accountRef.getOid() + " from focus " + focusOid);
OperationResult result = parentResult.createSubresult(OPERATION_UNLINK_ACCOUNT);
Collection<? extends ItemDelta> accountRefDeltas = ReferenceDelta.createModificationDeleteCollection(
FocusType.F_LINK_REF, getUserDefinition(), accountRef.clone());
try {
cacheRepositoryService.modifyObject(typeClass, focusOid, accountRefDeltas, result);
task.recordObjectActionExecuted(focusContext.getObjectAny(), typeClass, focusOid,
ChangeType.MODIFY, channel, null);
} catch (ObjectAlreadyExistsException ex) {
task.recordObjectActionExecuted(focusContext.getObjectAny(), typeClass, focusOid,
ChangeType.MODIFY, channel, ex);
result.recordFatalError(ex);
throw new SystemException(ex);
} catch (Throwable t) {
task.recordObjectActionExecuted(focusContext.getObjectAny(), typeClass, focusOid,
ChangeType.MODIFY, channel, t);
throw t;
} finally {
result.computeStatus();
ObjectDelta<F> userDelta = ObjectDelta.createModifyDelta(focusOid, accountRefDeltas, typeClass,
prismContext);
LensObjectDeltaOperation<F> userDeltaOp = LensUtil.createObjectDeltaOperation(userDelta, result,
focusContext, projCtx);
focusContext.addToExecutedDeltas(userDeltaOp);
}
}
private <F extends ObjectType> void updateSituationInShadow(Task task,
SynchronizationSituationType situation, LensFocusContext<F> focusContext,
LensProjectionContext projectionCtx, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException {
String projectionOid = projectionCtx.getOid();
OperationResult result = new OperationResult(OPERATION_UPDATE_SITUATION_ACCOUNT);
result.addArbitraryObjectAsParam("situation", situation);
result.addParam("accountRef", projectionOid);
PrismObject<ShadowType> account = null;
GetOperationOptions getOptions = GetOperationOptions.createNoFetch();
getOptions.setAllowNotFound(true);
try {
account = provisioning.getObject(ShadowType.class, projectionOid,
SelectorOptions.createCollection(getOptions), task, result);
} catch (Exception ex) {
LOGGER.trace("Problem with getting account, skipping modifying situation in account.");
return;
}
List<PropertyDelta<?>> syncSituationDeltas = SynchronizationUtils
.createSynchronizationSituationAndDescriptionDelta(account, situation, task.getChannel(),
projectionCtx.hasFullShadow());
try {
Utils.setRequestee(task, focusContext);
ProvisioningOperationOptions options = ProvisioningOperationOptions
.createCompletePostponed(false);
options.setDoNotDiscovery(true);
String changedOid = provisioning.modifyObject(ShadowType.class, projectionOid,
syncSituationDeltas, null, options, task, result);
// modifyProvisioningObject(AccountShadowType.class, accountRef,
// syncSituationDeltas,
// ProvisioningOperationOptions.createCompletePostponed(false),
// task, result);
projectionCtx.setSynchronizationSituationResolved(situation);
LOGGER.trace("Situation in projection {} was updated to {}.", projectionCtx, situation);
} catch (ObjectNotFoundException ex) {
// if the object not found exception is thrown, it's ok..probably
// the account was deleted by previous execution of changes..just
// log in the trace the message for the user..
LOGGER.trace(
"Situation in account could not be updated. Account not found on the resource. Skipping modifying situation in account");
return;
} catch (Exception ex) {
throw new SystemException(ex.getMessage(), ex);
} finally {
Utils.clearRequestee(task);
}
// if everything is OK, add result of the situation modification to the
// parent result
result.recordSuccess();
parentResult.addSubresult(result);
}
private <T extends ObjectType, F extends ObjectType> void executeDelta(ObjectDelta<T> objectDelta,
LensElementContext<T> objectContext, LensContext<F> context, ModelExecuteOptions options,
ResourceType resource, Task task, OperationResult parentResult)
throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException,
CommunicationException, ConfigurationException, SecurityViolationException,
ExpressionEvaluationException {
if (objectDelta == null) {
throw new IllegalArgumentException("Null change");
}
if (objectDelta.getOid() == null) {
objectDelta.setOid(objectContext.getOid());
}
objectDelta = computeDeltaToExecute(objectDelta, objectContext);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("computeDeltaToExecute returned:\n{}",
objectDelta != null ? objectDelta.debugDump() : "(null)");
}
if (objectDelta == null || objectDelta.isEmpty()) {
LOGGER.debug("Skipping execution of delta because it was already executed: {}", objectContext);
return;
}
if (InternalsConfig.consistencyChecks) {
objectDelta.checkConsistence(ConsistencyCheckScope.fromBoolean(consistencyChecks));
}
// Other types than focus types may not be definition-complete (e.g.
// accounts and resources are completed in provisioning)
if (FocusType.class.isAssignableFrom(objectDelta.getObjectTypeClass())) {
objectDelta.assertDefinitions();
}
LensUtil.setDeltaOldValue(objectContext, objectDelta);
if (LOGGER.isTraceEnabled()) {
logDeltaExecution(objectDelta, context, resource, null, task);
}
OperationResult result = parentResult.createSubresult(OPERATION_EXECUTE_DELTA);
try {
if (objectDelta.getChangeType() == ChangeType.ADD) {
executeAddition(objectDelta, context, objectContext, options, resource, task, result);
} else if (objectDelta.getChangeType() == ChangeType.MODIFY) {
executeModification(objectDelta, context, objectContext, options, resource, task, result);
} else if (objectDelta.getChangeType() == ChangeType.DELETE) {
executeDeletion(objectDelta, context, objectContext, options, resource, task, result);
}
// To make sure that the OID is set (e.g. after ADD operation)
LensUtil.setContextOid(context, objectContext, objectDelta.getOid());
} finally {
result.computeStatus();
if (objectContext != null) {
if (!objectDelta.hasCompleteDefinition()) {
throw new SchemaException("object delta does not have complete definition");
}
LensObjectDeltaOperation<T> objectDeltaOp = LensUtil.createObjectDeltaOperation(
objectDelta.clone(), result, objectContext, null, resource);
objectContext.addToExecutedDeltas(objectDeltaOp);
}
if (LOGGER.isDebugEnabled()) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("EXECUTION result {}", result.getLastSubresult());
} else {
// Execution of deltas was not logged yet
logDeltaExecution(objectDelta, context, resource, result.getLastSubresult(), task);
}
}
}
}
private <T extends ObjectType, F extends FocusType> void removeExecutedItemDeltas(
ObjectDelta<T> objectDelta, LensElementContext<T> objectContext) {
if (objectContext == null) {
return;
}
if (objectDelta == null || objectDelta.isEmpty()) {
return;
}
if (objectDelta.getModifications() == null || objectDelta.getModifications().isEmpty()) {
return;
}
List<LensObjectDeltaOperation<T>> executedDeltas = objectContext.getExecutedDeltas();
for (LensObjectDeltaOperation<T> executedDelta : executedDeltas) {
ObjectDelta<T> executed = executedDelta.getObjectDelta();
Iterator<? extends ItemDelta> objectDeltaIterator = objectDelta.getModifications().iterator();
while (objectDeltaIterator.hasNext()) {
ItemDelta d = objectDeltaIterator.next();
if (executed.containsModification(d, true, true) || d.isEmpty()) {
objectDeltaIterator.remove();
}
}
}
}
// TODO beware - what if the delta was executed but not successfully?
private <T extends ObjectType, F extends FocusType> boolean alreadyExecuted(ObjectDelta<T> objectDelta,
LensElementContext<T> objectContext) {
if (objectContext == null) {
return false;
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Checking for already executed delta:\n{}\nIn deltas:\n{}", objectDelta.debugDump(),
DebugUtil.debugDump(objectContext.getExecutedDeltas()));
}
return ObjectDeltaOperation.containsDelta(objectContext.getExecutedDeltas(), objectDelta);
}
/**
* Was this object already added? (temporary method, should be removed soon)
*/
private <T extends ObjectType> boolean wasAdded(List<LensObjectDeltaOperation<T>> executedOperations,
String oid) {
for (LensObjectDeltaOperation operation : executedOperations) {
if (operation.getObjectDelta().isAdd() && oid.equals(operation.getObjectDelta().getOid())
&& !operation.getExecutionResult().isFatalError()) {
return true;
}
}
return false;
}
/**
* Computes delta to execute, given a list of already executes deltas. See
* below.
*/
private <T extends ObjectType> ObjectDelta<T> computeDeltaToExecute(ObjectDelta<T> objectDelta,
LensElementContext<T> objectContext) {
if (objectContext == null) {
return objectDelta;
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Computing delta to execute from delta:\n{}\nGiven these executed deltas:\n{}",
objectDelta.debugDump(), DebugUtil.debugDump(objectContext.getExecutedDeltas()));
}
List<LensObjectDeltaOperation<T>> executedDeltas = objectContext.getExecutedDeltas();
return computeDiffDelta(executedDeltas, objectDelta);
}
/**
* Compute a "difference delta" - given that executedDeltas were executed,
* and objectDelta is about to be executed; eliminates parts that have
* already been done. It is meant as a kind of optimization (for MODIFY
* deltas) and error avoidance (for ADD deltas).
*
* Explanation for ADD deltas: there are situations where an execution wave
* is restarted - when unexpected AlreadyExistsException is reported from
* provisioning. However, in such cases, duplicate ADD Focus deltas were
* generated. So we (TEMPORARILY!) decided to filter them out here.
*
* Unfortunately, this mechanism is not well-defined, and seems to work more
* "by accident" than "by design". It should be replaced with something more
* serious. Perhaps by re-reading current focus state when repeating a wave?
* Actually, it is a supplement for rewriting ADD->MODIFY deltas in
* LensElementContext.getFixedPrimaryDelta. That method converts primary
* deltas (and as far as I know, that is the only place where this problem
* should occur). Nevertheless, for historical and safety reasons I keep
* also the processing in this method.
*
* Anyway, currently it treats only two cases: 1) if the objectDelta is
* present in the list of executed deltas 2) if the objectDelta is ADD, and
* another ADD delta is there (then the difference is computed)
*
*/
private <T extends ObjectType> ObjectDelta<T> computeDiffDelta(
List<? extends ObjectDeltaOperation<T>> executedDeltas, ObjectDelta<T> objectDelta) {
if (executedDeltas == null || executedDeltas.isEmpty()) {
return objectDelta;
}
// any delta related to our OID, not ending with fatal error
ObjectDeltaOperation<T> lastRelated = findLastRelatedDelta(executedDeltas, objectDelta);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("findLastRelatedDelta returned:\n{}",
lastRelated != null ? lastRelated.debugDump() : "(null)");
}
if (lastRelated == null) {
return objectDelta; // nothing found, let us apply our delta
}
if (lastRelated.getExecutionResult().isSuccess() && lastRelated.containsDelta(objectDelta)) {
return null; // case 1 - exact match found with SUCCESS result,
// let's skip the processing of our delta
}
if (!objectDelta.isAdd()) {
return objectDelta; // MODIFY or DELETE delta - we may safely apply
// it (not 100% sure about DELETE case)
}
// determine if we got case 2
if (lastRelated.getObjectDelta().isDelete()) {
return objectDelta; // we can (and should) apply the ADD delta as a
// whole, because the object was deleted
}
// let us treat the most simple case here - meaning we have existing ADD
// delta and nothing more
// TODO add more sophistication if needed
if (!lastRelated.getObjectDelta().isAdd()) {
return objectDelta; // this will probably fail, but ...
}
// at this point we know that ADD was more-or-less successfully
// executed, so let's compute the difference, creating a MODIFY delta
PrismObject<T> alreadyAdded = lastRelated.getObjectDelta().getObjectToAdd();
PrismObject<T> toBeAddedNow = objectDelta.getObjectToAdd();
return alreadyAdded.diff(toBeAddedNow);
}
private <T extends ObjectType> ObjectDeltaOperation<T> findLastRelatedDelta(
List<? extends ObjectDeltaOperation<T>> executedDeltas, ObjectDelta<T> objectDelta) {
for (int i = executedDeltas.size() - 1; i >= 0; i--) {
ObjectDeltaOperation<T> currentOdo = executedDeltas.get(i);
if (!currentOdo.getExecutionResult().isFatalError()) {
ObjectDelta<T> current = currentOdo.getObjectDelta();
if (current.equals(objectDelta)) {
return currentOdo;
}
String oid1 = current.isAdd() ? current.getObjectToAdd().getOid() : current.getOid();
String oid2 = objectDelta.isAdd() ? objectDelta.getObjectToAdd().getOid()
: objectDelta.getOid();
if (oid1 != null && oid2 != null) {
if (oid1.equals(oid2)) {
return currentOdo;
}
continue;
}
// ADD-MODIFY and ADD-DELETE combinations lead to applying whole
// delta (as a result of computeDiffDelta)
// so we can be lazy and check only ADD-ADD combinations here...
if (!current.isAdd() || !objectDelta.isAdd()) {
continue;
}
// we simply check the type (for focus objects) and
// resource+kind+intent (for shadows)
PrismObject<T> currentObject = current.getObjectToAdd();
PrismObject<T> objectTypeToAdd = objectDelta.getObjectToAdd();
Class currentObjectClass = currentObject.getCompileTimeClass();
Class objectTypeToAddClass = objectTypeToAdd.getCompileTimeClass();
if (currentObjectClass == null || !currentObjectClass.equals(objectTypeToAddClass)) {
continue;
}