-
Notifications
You must be signed in to change notification settings - Fork 188
/
ChangeExecutor.java
1881 lines (1651 loc) · 97.2 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-2019 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
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.prism.PrismContainerValue.asContainerables;
import static com.evolveum.midpoint.schema.internals.InternalsConfig.consistencyChecks;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.xml.bind.JAXBElement;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import com.evolveum.midpoint.model.api.context.SynchronizationIntent;
import com.evolveum.midpoint.model.impl.lens.assignments.AssignmentSpec;
import com.evolveum.midpoint.wf.api.WorkflowManager;
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 com.evolveum.midpoint.common.Clock;
import com.evolveum.midpoint.common.SynchronizationUtils;
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.common.expression.ExpressionEnvironment;
import com.evolveum.midpoint.model.common.expression.ModelExpressionThreadLocalHolder;
import com.evolveum.midpoint.model.impl.lens.projector.credentials.CredentialsProcessor;
import com.evolveum.midpoint.model.impl.lens.projector.focus.FocusConstraintsChecker;
import com.evolveum.midpoint.model.impl.util.ModelImplUtils;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.prism.delta.*;
import com.evolveum.midpoint.prism.equivalence.EquivalenceStrategy;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.xnode.PrimitiveXNode;
import com.evolveum.midpoint.prism.xnode.XNodeFactory;
import com.evolveum.midpoint.provisioning.api.ProvisioningOperationOptions;
import com.evolveum.midpoint.provisioning.api.ProvisioningService;
import com.evolveum.midpoint.repo.api.*;
import com.evolveum.midpoint.repo.common.expression.*;
import com.evolveum.midpoint.repo.common.util.RepoCommonUtils;
import com.evolveum.midpoint.schema.*;
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.expression.ExpressionProfile;
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.ExceptionUtil;
import com.evolveum.midpoint.schema.util.MiscSchemaUtil;
import com.evolveum.midpoint.schema.util.ResourceTypeUtil;
import com.evolveum.midpoint.schema.util.ShadowUtil;
import com.evolveum.midpoint.security.api.MidPointPrincipal;
import com.evolveum.midpoint.security.api.OwnerResolver;
import com.evolveum.midpoint.security.api.SecurityContextManager;
import com.evolveum.midpoint.security.enforcer.api.AuthorizationParameters;
import com.evolveum.midpoint.security.enforcer.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.ProtectedStringType;
import com.evolveum.prism.xml.ns._public.types_3.RawType;
/**
* @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_IN_SHADOW = ChangeExecutor.class.getName() + ".updateSituationInShadow";
@Autowired private TaskManager taskManager;
@Autowired(required = false) private WorkflowManager workflowManager; // not available e.g. during tests
@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 SecurityContextManager securityContextManager;
@Autowired private Clock clock;
@Autowired private ModelObjectResolver objectResolver;
@Autowired private OperationalDataManager metadataManager;
@Autowired private CredentialsProcessor credentialsProcessor;
@Autowired private ClockworkConflictResolver clockworkConflictResolver;
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, PreconditionViolationException, PolicyViolationException {
OperationResult result = parentResult.createSubresult(OPERATION_EXECUTE);
try {
// FOCUS
context.checkAbortRequested();
LensFocusContext<O> focusContext = context.getFocusContext();
if (focusContext != null) {
ObjectDelta<O> focusDelta = focusContext.getWaveExecutableDelta(context.getExecutionWave());
focusDelta = applyPendingObjectPolicyStateModifications(focusContext, focusDelta);
focusDelta = applyPendingAssignmentPolicyStateModifications(focusContext, focusDelta);
if (focusDelta == null && !context.hasProjectionChange()) {
LOGGER.trace("Skipping focus change execute, because user delta is null");
} else {
if (focusDelta == null) {
focusDelta = focusContext.getObjectAny().createModifyDelta();
}
ArchetypePolicyType archetypePolicy = focusContext.getArchetypePolicyType();
applyObjectPolicy(focusContext, focusDelta, archetypePolicy);
OperationResult subResult = result.createSubresult(
OPERATION_EXECUTE_FOCUS + "." + focusContext.getObjectTypeClass().getSimpleName());
try {
// Will remove credential deltas or hash them
focusDelta = credentialsProcessor.transformFocusExecutionDelta(context, focusDelta);
} catch (EncryptionException e) {
recordFatalError(subResult, result, null, e);
result.computeStatus();
throw new SystemException(e.getMessage(), e);
}
applyLastProvisioningTimestamp(context, focusDelta);
try {
context.reportProgress(new ProgressInformation(FOCUS_OPERATION, ENTERING));
ConflictResolutionType conflictResolution = ModelExecuteOptions
.getFocusConflictResolution(context.getOptions());
executeDelta(focusDelta, focusContext, context, null, conflictResolution, null, task, subResult);
if (focusDelta.isAdd() && focusDelta.getOid() != null) {
clockworkConflictResolver.createConflictWatcherAfterFocusAddition(context, focusDelta.getOid(),
focusDelta.getObjectToAdd().getVersion());
}
subResult.computeStatus();
} catch (SchemaException | ObjectNotFoundException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException | RuntimeException e) {
recordFatalError(subResult, result, null, e);
throw e;
} catch (PreconditionViolationException e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Modification precondition failed for {}: {}", focusContext.getHumanReadableName(),
e.getMessage());
}
// TODO: fatal error if the conflict resolution is "error" (later)
result.recordHandledError(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));
}
}
}
// PROJECTIONS
context.checkAbortRequested();
boolean restartRequested = false;
for (LensProjectionContext projCtx : context.getProjectionContexts()) {
if (projCtx.getWave() != context.getExecutionWave()) {
LOGGER.trace("Skipping projection context {} because its wave ({}) is different from execution wave ({})",
projCtx.toHumanReadableString(), projCtx.getWave(), context.getExecutionWave());
continue;
}
if (!projCtx.isCanProject()) {
LOGGER.trace("Skipping projection context {} because canProject is false", projCtx.toHumanReadableString());
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.subresult(OPERATION_EXECUTE_PROJECTION + "." + projCtx.getObjectTypeClass().getSimpleName())
.addParam("resource", projCtx.getResource())
.addArbitraryObjectAsContext("discriminator", projCtx.getResourceShadowDiscriminator())
.build();
PrismObject<ShadowType> shadowAfterModification = null;
try {
LOGGER.trace("Executing projection context {}", projCtx.toHumanReadableString());
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 = prismContext.deltaFactory().object()
.createDeleteDelta(projCtx.getObjectTypeClass(), projCtx.getOid());
}
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 = prismContext.deltaFactory().object()
.createDeleteDelta(projCtx.getObjectTypeClass(), projCtx.getOid());
}
}
if (projDelta != null && projDelta.isDelete()) {
shadowAfterModification = executeDelta(projDelta, projCtx, context, null, null, projCtx.getResource(), task,
subResult);
}
} else {
if (projDelta == null || projDelta.isEmpty()) {
LOGGER.trace("No change for {}", projCtx.getResourceShadowDiscriminator());
shadowAfterModification = projCtx.getObjectCurrent();
if (focusContext != null) {
updateLinks(context, focusContext, projCtx, shadowAfterModification, 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;
}
}
shadowAfterModification = executeDelta(projDelta, projCtx, context, null, null, projCtx.getResource(), task, subResult);
if (projCtx.isAdd() && shadowAfterModification != null) {
projCtx.setExists(true);
}
}
subResult.computeStatus();
if (focusContext != null) {
updateLinks(context, focusContext, projCtx, shadowAfterModification, task, subResult);
}
executeReconciliationScript(projCtx, context, BeforeAfterType.AFTER, task, subResult);
subResult.computeStatus();
subResult.recordNotApplicableIfUnknown();
} catch (SchemaException | ObjectNotFoundException | PreconditionViolationException | CommunicationException |
ConfigurationException | SecurityViolationException | PolicyViolationException | ExpressionEvaluationException | RuntimeException | Error e) {
recordProjectionExecutionException(e, projCtx, subResult, SynchronizationPolicyDecision.BROKEN);
// We still want to update the links here. E.g. this may be live sync case where we discovered new account
// try to reconcile, but the reconciliation fails. We still want this shadow linked to user.
if (focusContext != null) {
updateLinks(context, focusContext, projCtx, shadowAfterModification, task, subResult);
}
ModelImplUtils.handleConnectorErrorCriticality(projCtx.getResource(), e, subResult);
} catch (ObjectAlreadyExistsException e) {
// This exception is quite special. We have to decide how bad this really is.
// This may be rename conflict. Which would be bad.
// Or this may be attempt to create account that already exists and just needs
// to be linked. Which is no big deal and consistency mechanism (discovery) will
// easily handle that. In that case it is done in "another task" which is
// quasi-asynchornously executed from provisioning by calling notifyChange.
// Once that is done then the account is already linked. And all we need to do
// is to restart this whole operation.
// 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)) {
// This is the bad case. Currently we do not do anything more intelligent than to look for
// repeated error. If we get OAEE twice then this is bad and we thow up.
// TODO: do something smarter here
LOGGER.debug("Repeated ObjectAlreadyExistsException detected, marking projection {} as broken", projCtx.toHumanReadableString());
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();
restartRequested = true;
LOGGER.debug("ObjectAlreadyExistsException for projection {}, requesting projector restart", projCtx.toHumanReadableString());
// we will process remaining projections when retrying the wave
break;
} finally {
context.reportProgress(new ProgressInformation(RESOURCE_OBJECT_OPERATION,
projCtx.getResourceShadowDiscriminator(), subResult));
}
}
// Result computation here needs to be slightly different
result.computeStatusComposite();
return restartRequested;
} catch (Throwable t) {
result.recordThrowableIfNeeded(t); // last resort: to avoid UNKNOWN subresults
throw t;
}
}
private <O extends ObjectType> ObjectDelta<O> applyPendingObjectPolicyStateModifications(LensFocusContext<O> focusContext,
ObjectDelta<O> focusDelta) throws SchemaException {
for (ItemDelta<?, ?> itemDelta : focusContext.getPendingObjectPolicyStateModifications()) {
focusDelta = focusContext.swallowToDelta(focusDelta, itemDelta);
}
focusContext.clearPendingObjectPolicyStateModifications();
return focusDelta;
}
private <O extends ObjectType> ObjectDelta<O> applyPendingAssignmentPolicyStateModifications(LensFocusContext<O> focusContext, ObjectDelta<O> focusDelta)
throws SchemaException {
for (Map.Entry<AssignmentSpec, List<ItemDelta<?, ?>>> entry : focusContext
.getPendingAssignmentPolicyStateModifications().entrySet()) {
PlusMinusZero mode = entry.getKey().mode;
if (mode == PlusMinusZero.MINUS) {
continue; // this assignment is being thrown out anyway, so let's ignore it (at least for now)
}
AssignmentType assignmentToFind = entry.getKey().assignment;
List<ItemDelta<?, ?>> modifications = entry.getValue();
if (modifications.isEmpty()) {
continue;
}
LOGGER.trace("Applying policy state modifications for {} ({}):\n{}", assignmentToFind, mode,
DebugUtil.debugDumpLazily(modifications));
if (mode == PlusMinusZero.ZERO) {
if (assignmentToFind.getId() == null) {
throw new IllegalStateException("Existing assignment with null id: " + assignmentToFind);
}
for (ItemDelta<?, ?> modification : modifications) {
focusDelta = focusContext.swallowToDelta(focusDelta, modification);
}
} else {
assert mode == PlusMinusZero.PLUS;
if (focusDelta != null && focusDelta.isAdd()) {
swallowIntoValues(((FocusType) focusDelta.getObjectToAdd().asObjectable()).getAssignment(),
assignmentToFind, modifications);
} else {
ContainerDelta<AssignmentType> assignmentDelta = focusDelta != null ?
focusDelta.findContainerDelta(FocusType.F_ASSIGNMENT) : null;
if (assignmentDelta == null) {
throw new IllegalStateException(
"We have 'plus' assignment to modify but there's no assignment delta. Assignment="
+ assignmentToFind + ", objectDelta=" + focusDelta);
}
if (assignmentDelta.isReplace()) {
swallowIntoValues(asContainerables(assignmentDelta.getValuesToReplace()), assignmentToFind,
modifications);
} else if (assignmentDelta.isAdd()) {
swallowIntoValues(asContainerables(assignmentDelta.getValuesToAdd()), assignmentToFind,
modifications);
} else {
throw new IllegalStateException(
"We have 'plus' assignment to modify but there're no values to add or replace in assignment delta. Assignment="
+ assignmentToFind + ", objectDelta=" + focusDelta);
}
}
}
}
focusContext.clearPendingAssignmentPolicyStateModifications();
return focusDelta;
}
private void swallowIntoValues(Collection<AssignmentType> assignments, AssignmentType assignmentToFind, List<ItemDelta<?, ?>> modifications)
throws SchemaException {
for (AssignmentType assignment : assignments) {
PrismContainerValue<?> pcv = assignment.asPrismContainerValue();
PrismContainerValue<?> pcvToFind = assignmentToFind.asPrismContainerValue();
if (pcv.representsSameValue(pcvToFind, false) || pcv.equals(pcvToFind, EquivalenceStrategy.REAL_VALUE_CONSIDER_DIFFERENT_IDS)) {
// TODO what if ID of the assignment being added is changed in repo? Hopefully it will be not.
for (ItemDelta<?, ?> modification : modifications) {
ItemPath newParentPath = modification.getParentPath().rest(2); // killing assignment + ID
ItemDelta<?, ?> pathRelativeModification = modification.cloneWithChangedParentPath(newParentPath);
pathRelativeModification.applyTo(pcv);
}
return;
}
}
// TODO change to warning
throw new IllegalStateException("We have 'plus' assignment to modify but it couldn't be found in assignment delta. Assignment=" + assignmentToFind + ", new assignments=" + assignments);
}
private <O extends ObjectType> void applyLastProvisioningTimestamp(LensContext<O> context, ObjectDelta<O> focusDelta) throws SchemaException {
if (!context.hasProjectionChange()) {
return;
}
if (focusDelta.isAdd()) {
PrismObject<O> objectToAdd = focusDelta.getObjectToAdd();
PrismContainer<MetadataType> metadataContainer = objectToAdd.findOrCreateContainer(ObjectType.F_METADATA);
metadataContainer.getRealValue().setLastProvisioningTimestamp(clock.currentTimeXMLGregorianCalendar());
} else if (focusDelta.isModify()) {
PropertyDelta<XMLGregorianCalendar> provTimestampDelta = prismContext.deltaFactory().property().createModificationReplaceProperty(
ItemPath.create(ObjectType.F_METADATA, MetadataType.F_LAST_PROVISIONING_TIMESTAMP),
context.getFocusContext().getObjectDefinition(),
clock.currentTimeXMLGregorianCalendar());
focusDelta.addModification(provTimestampDelta);
}
}
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 = ItemDeltaCollectionsUtil
.findItemDeltasSubPath(modifications1, ShadowType.F_ATTRIBUTES);
Collection<? extends ItemDelta<?, ?>> attrDeltas2 = ItemDeltaCollectionsUtil
.findItemDeltasSubPath(modifications2, ShadowType.F_ATTRIBUTES);
//noinspection unchecked,RedundantCast
return MiscUtil.unorderedCollectionEquals((Collection) attrDeltas1, (Collection) 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, ArchetypePolicyType archetypePolicy) {
if (archetypePolicy == null) {
return;
}
PrismObject<O> objectNew = focusContext.getObjectNew();
if (focusDelta.isAdd() && objectNew.getOid() == null) {
for (ItemConstraintType itemConstraintType : archetypePolicy.getItemConstraint()) {
processItemConstraint(focusContext, objectNew, itemConstraintType);
}
// Deprecated
for (ItemConstraintType itemConstraintType : archetypePolicy.getPropertyConstraint()) {
processItemConstraint(focusContext, objectNew, itemConstraintType);
}
}
}
private <O extends ObjectType> void processItemConstraint(LensFocusContext<O> focusContext, PrismObject<O> objectNew, ItemConstraintType itemConstraintType) {
if (BooleanUtils.isTrue(itemConstraintType.isOidBound())) {
ItemPath itemPath = itemConstraintType.getPath().getItemPath();
PrismProperty<Object> prop = objectNew.findProperty(itemPath);
String stringValue = prop.getRealValue().toString();
focusContext.setOid(stringValue);
}
}
private <P extends ObjectType> void recordProjectionExecutionException(Throwable e,
LensProjectionContext accCtx, OperationResult subResult, SynchronizationPolicyDecision decision) {
subResult.recordFatalError(e);
LOGGER.error("Error executing changes for {}: {}", 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(LensContext<?> context,
LensFocusContext<O> focusObjectContext, LensProjectionContext projCtx,
PrismObject<ShadowType> shadowAfterModification,
Task task, OperationResult result) throws ObjectNotFoundException, SchemaException {
if (focusObjectContext == null) {
return;
}
Class<O> objectTypeClass = focusObjectContext.getObjectTypeClass();
if (!FocusType.class.isAssignableFrom(objectTypeClass)) {
return;
}
//noinspection unchecked
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.error("Projection {} has null OID, this should not happen, context:\n{}", projCtx.toHumanReadableString(), projCtx.debugDump());
throw new IllegalStateException("Projection " + projCtx.toHumanReadableString() + " has null OID, this should not happen");
}
if (linkShouldExist(focusContext, projCtx, shadowAfterModification, 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, context, 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, context, 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);
}
}
}
}
}
// 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, context, focusObjectContext, projCtx, result);
// Not linked, that's OK
}
}
private <F extends FocusType> boolean linkShouldExist(LensFocusContext<F> focusContext, LensProjectionContext projCtx, PrismObject<ShadowType> shadowAfterModification, OperationResult result) {
if (focusContext.isDelete()) {
// if we delete focus, link doesn't exist anymore, but be sure, that the situation is updated in shadow
return false;
}
if (!projCtx.isShadowExistsInRepo()) {
// Nothing to link to
return false;
}
if (projCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.UNLINK) {
return false;
}
if (isEmptyThombstone(projCtx)) {
return false;
}
if (projCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.DELETE
|| projCtx.isDelete()) {
return shadowAfterModification != null;
}
if (projCtx.hasPendingOperations()) {
return true;
}
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().isTombstone()
&& 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 = prismContext.itemFactory().createReferenceValue();
linkRef.setOid(shadowOid);
linkRef.setTargetType(ShadowType.COMPLEX_TYPE);
Collection<? extends ItemDelta> linkRefDeltas = prismContext.deltaFactory().reference()
.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 = prismContext.deltaFactory().object().createModifyDelta(userOid, linkRefDeltas, typeClass
);
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 {} from focus {}", accountRef.getOid(), focusOid);
OperationResult result = parentResult.createSubresult(OPERATION_UNLINK_ACCOUNT);
Collection<? extends ItemDelta> accountRefDeltas = prismContext.deltaFactory().reference().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 = prismContext.deltaFactory().object()
.createModifyDelta(focusOid, accountRefDeltas, typeClass
);
LensObjectDeltaOperation<F> userDeltaOp = LensUtil.createObjectDeltaOperation(userDelta, result,
focusContext, projCtx);
focusContext.addToExecutedDeltas(userDeltaOp);
}
}
private <F extends ObjectType> void updateSituationInShadow(Task task, SynchronizationSituationType newSituation,
LensContext<?> context, LensFocusContext<F> focusContext, LensProjectionContext projectionCtx,
OperationResult parentResult) throws SchemaException {
String projectionOid = projectionCtx.getOid();
OperationResult result = parentResult.createMinorSubresult(OPERATION_UPDATE_SITUATION_IN_SHADOW);
result.addArbitraryObjectAsParam("situation", newSituation);
result.addParam("accountRef", projectionOid);
projectionCtx.setSynchronizationSituationResolved(newSituation);
PrismObject<ShadowType> currentShadow;
GetOperationOptions getOptions = GetOperationOptions.createNoFetch();
getOptions.setAllowNotFound(true);
try {
// TODO consider skipping this operation - at least in some cases
currentShadow = provisioning.getObject(ShadowType.class, projectionOid,
SelectorOptions.createCollection(getOptions), task, result);
} catch (ObjectNotFoundException ex) {
LOGGER.trace("Shadow is gone, skipping modifying situation in shadow.");
result.recordSuccess();
return;
} catch (Exception ex) {
LOGGER.trace("Problem with getting shadow, skipping modifying situation in shadow.");
result.recordPartialError(ex);
return;
}
SynchronizationSituationType currentSynchronizationSituation = currentShadow.asObjectable().getSynchronizationSituation();
if (currentSynchronizationSituation == SynchronizationSituationType.DELETED && ShadowUtil.isDead(currentShadow.asObjectable())) {
LOGGER.trace("Skipping update of synchronization situation for deleted dead shadow");
result.recordSuccess();
return;
}
InternalsConfigurationType internalsConfig = context.getInternalsConfiguration();
boolean cansSkip =
internalsConfig != null && internalsConfig.getSynchronizationSituationUpdating() != null &&
Boolean.TRUE.equals(internalsConfig.getSynchronizationSituationUpdating().isSkipWhenNoChange());
if (cansSkip) {
if (newSituation == currentSynchronizationSituation) {
LOGGER.trace("Skipping update of synchronization situation because there is no change ({})",
currentSynchronizationSituation);
result.recordSuccess();
return;
} else {
LOGGER.trace("Updating synchronization situation {} -> {}", currentSynchronizationSituation, newSituation);
}
}
XMLGregorianCalendar now = clock.currentTimeXMLGregorianCalendar();
List<PropertyDelta<?>> syncSituationDeltas = SynchronizationUtils
.createSynchronizationSituationAndDescriptionDelta(currentShadow, newSituation, task.getChannel(),
projectionCtx.hasFullShadow(), now, prismContext);
try {
ModelImplUtils.setRequestee(task, focusContext);
ProvisioningOperationOptions options = ProvisioningOperationOptions.createCompletePostponed(false);
options.setDoNotDiscovery(true);
provisioning.modifyObject(ShadowType.class, projectionOid, syncSituationDeltas, null, options, task, result);
LOGGER.trace("Situation in projection {} was updated to {}.", projectionCtx, newSituation);
} 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.debug(
"Situation in account could not be updated. Account not found on the resource. Skipping modifying situation in account");
return;
} catch (Exception ex) {
result.recordFatalError(ex);
throw new SystemException(ex.getMessage(), ex);
} finally {
ModelImplUtils.clearRequestee(task);
}
// if everything is OK, add result of the situation modification to the
// parent result
result.recordSuccess();
}
/**
* @return Returns estimate of the object after modification. Or null if the object was deleted.
* NOTE: this is only partially implemented (only for shadow delete).
*/
private <T extends ObjectType, F extends ObjectType> PrismObject<T> executeDelta(ObjectDelta<T> objectDelta,
LensElementContext<T> objectContext, LensContext<F> context, ModelExecuteOptions options,
ConflictResolutionType conflictResolution, ResourceType resource, Task task, OperationResult parentResult)
throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException,
CommunicationException, ConfigurationException, SecurityViolationException,
PolicyViolationException, ExpressionEvaluationException, PreconditionViolationException {
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(1) : "(null)");
}
if (objectDelta == null || objectDelta.isEmpty()) {
LOGGER.debug("Skipping execution of delta because it was already executed: {}", objectContext);
return objectContext.getObjectCurrent();
}
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);
PrismObject<T> objectAfterModification = null;
try {
if (objectDelta.getChangeType() == ChangeType.ADD) {
objectAfterModification = executeAddition(objectDelta, context, objectContext, options, resource, task, result);
} else if (objectDelta.getChangeType() == ChangeType.MODIFY) {
executeModification(objectDelta, context, objectContext, options, conflictResolution, resource, task, result);
} else if (objectDelta.getChangeType() == ChangeType.DELETE) {
objectAfterModification = 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);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Recording executed delta:\n{}", objectDeltaOp.shorterDebugDump(1));
}
objectContext.addToExecutedDeltas(objectDeltaOp);
if (result.isTracingNormal(ModelExecuteDeltaTraceType.class)) {
TraceType trace = new ModelExecuteDeltaTraceType(prismContext)
.delta(objectDeltaOp.clone().toLensObjectDeltaOperationType()); // todo kill operation result?
result.addTrace(trace);
}
} else {
if (result.isTracingNormal(ModelExecuteDeltaTraceType.class)) {
LensObjectDeltaOperation<T> objectDeltaOp = new LensObjectDeltaOperation<>(objectDelta); // todo
TraceType trace = new ModelExecuteDeltaTraceType(prismContext)
.delta(objectDeltaOp.toLensObjectDeltaOperationType());
result.addTrace(trace);
}
}
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);
}
}
}
return objectAfterModification;
}
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) {