/
ShadowCache.java
3175 lines (2702 loc) · 171 KB
/
ShadowCache.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.provisioning.impl;
import com.evolveum.midpoint.common.Clock;
import com.evolveum.midpoint.common.crypto.CryptoUtil;
import com.evolveum.midpoint.common.refinery.RefinedAssociationDefinition;
import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition;
import com.evolveum.midpoint.common.refinery.ShadowDiscriminatorObjectDelta;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.prism.crypto.Protector;
import com.evolveum.midpoint.prism.delta.*;
import com.evolveum.midpoint.prism.match.MatchingRuleRegistry;
import com.evolveum.midpoint.prism.path.*;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.*;
import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import com.evolveum.midpoint.provisioning.api.*;
import com.evolveum.midpoint.provisioning.impl.errorhandling.ErrorHandler;
import com.evolveum.midpoint.provisioning.impl.errorhandling.ErrorHandlerLocator;
import com.evolveum.midpoint.provisioning.impl.shadowmanager.ShadowManager;
import com.evolveum.midpoint.provisioning.ucf.api.*;
import com.evolveum.midpoint.provisioning.util.ProvisioningUtil;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.schema.*;
import com.evolveum.midpoint.schema.cache.CacheConfigurationManager;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.internals.InternalCounters;
import com.evolveum.midpoint.schema.internals.InternalMonitor;
import com.evolveum.midpoint.schema.internals.InternalsConfig;
import com.evolveum.midpoint.schema.processor.*;
import com.evolveum.midpoint.schema.processor.ObjectFactory;
import com.evolveum.midpoint.schema.result.AsynchronousOperationResult;
import com.evolveum.midpoint.schema.result.AsynchronousOperationReturnValue;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.schema.util.ObjectQueryUtil;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.schema.util.ResourceTypeUtil;
import com.evolveum.midpoint.schema.util.ShadowUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskManager;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.Holder;
import com.evolveum.midpoint.util.QNameUtil;
import com.evolveum.midpoint.util.exception.*;
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.midpoint.xml.ns._public.resource.capabilities_3.*;
import com.evolveum.prism.xml.ns._public.types_3.ChangeTypeType;
import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import java.util.*;
/**
* Shadow cache is a facade that covers all the operations with shadows. It
* takes care of splitting the operations between repository and resource,
* merging the data back, handling the errors and generally controlling the
* process.
*
* The two principal classes that do the operations are:
* ResourceObjectConvertor: executes operations on resource
* ShadowManager: executes operations in the repository
*
* @author Radovan Semancik
* @author Katarina Valalikova
*
*/
@Component
public class ShadowCache {
private static final String OP_DELAYED_OPERATION = ShadowCache.class.getName() + ".delayedOperation";
private static final String OP_OPERATION_RETRY = ShadowCache.class.getName() + ".operationRetry";
private static final String OP_RESOURCE_OPERATION = ShadowCache.class.getName() + ".resourceOperation";
private static final String OP_REFRESH_RETRY = ShadowCache.class.getName() + ".refreshRetry";
@Autowired
@Qualifier("cacheRepositoryService")
private RepositoryService repositoryService;
@Autowired private ErrorHandlerLocator errorHandlerLocator;
@Autowired private ResourceManager resourceManager;
@Autowired private Clock clock;
@Autowired private PrismContext prismContext;
@Autowired private SchemaHelper schemaHelper;
@Autowired private ResourceObjectConverter resourceObjectConverter;
@Autowired private ShadowCaretaker shadowCaretaker;
@Autowired private MatchingRuleRegistry matchingRuleRegistry;
@Autowired private RelationRegistry relationRegistry;
@Autowired protected ShadowManager shadowManager;
@Autowired private ChangeNotificationDispatcher operationListener;
@Autowired private AccessChecker accessChecker;
@Autowired private TaskManager taskManager;
@Autowired private ChangeNotificationDispatcher changeNotificationDispatcher;
@Autowired private ProvisioningContextFactory ctxFactory;
@Autowired private Protector protector;
@Autowired private CacheConfigurationManager cacheConfigurationManager;
private static final Trace LOGGER = TraceManager.getTrace(ShadowCache.class);
/**
* Get the value of repositoryService.
*
* DO NOT USE. Only ShadowManager should access repository
*
* @return the value of repositoryService
*/
@Deprecated
public RepositoryService getRepositoryService() {
return repositoryService;
}
public PrismContext getPrismContext() {
return prismContext;
}
public PrismObject<ShadowType> getShadow(String oid, PrismObject<ShadowType> repositoryShadow,
Collection<ResourceAttribute<?>> identifiersOverride, Collection<SelectorOptions<GetOperationOptions>> options,
Task task, OperationResult parentResult)
throws ObjectNotFoundException, CommunicationException, SchemaException,
ConfigurationException, SecurityViolationException, ExpressionEvaluationException, EncryptionException {
Validate.notNull(oid, "Object id must not be null.");
if (repositoryShadow == null) {
LOGGER.trace("Start getting object with oid {}; identifiers override = {}", oid, identifiersOverride);
} else {
LOGGER.trace("Start getting object {}; identifiers override = {}", repositoryShadow, identifiersOverride);
}
GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options);
// We are using parent result directly, not creating subresult.
// We want to hide the existence of shadow cache from the user.
// Get the shadow from repository. There are identifiers that we need
// for accessing the object by UCF.Later, the repository object may
// have a fully cached object from the resource.
if (repositoryShadow == null) {
repositoryShadow = repositoryService.getObject(ShadowType.class, oid, null, parentResult);
LOGGER.trace("Got repository shadow object:\n{}", repositoryShadow.debugDumpLazily());
}
// Sanity check
if (!oid.equals(repositoryShadow.getOid())) {
parentResult.recordFatalError("Provided OID is not equal to OID of repository shadow");
throw new IllegalArgumentException("Provided OID is not equal to OID of repository shadow");
}
ProvisioningContext ctx = ctxFactory.create(repositoryShadow, task, parentResult);
ctx.setGetOperationOptions(options);
ctx.assertDefinition();
shadowCaretaker.applyAttributesDefinition(ctx, repositoryShadow);
ResourceType resource = ctx.getResource();
XMLGregorianCalendar now = clock.currentTimeXMLGregorianCalendar();
if (GetOperationOptions.isNoFetch(rootOptions) || GetOperationOptions.isRaw(rootOptions)) {
return processNoFetchGet(ctx, repositoryShadow, options, now, task, parentResult);
}
if (!ResourceTypeUtil.isReadCapabilityEnabled(resource)) {
UnsupportedOperationException e = new UnsupportedOperationException("Resource does not support 'read' operation");
parentResult.recordFatalError(e);
throw e;
}
if (shouldRefreshOnRead(resource, rootOptions)) {
LOGGER.trace("Refreshing {} before reading", repositoryShadow);
ProvisioningOperationOptions refreshOpts = toProvisioningOperationOptions(rootOptions);
RefreshShadowOperation refreshShadowOperation = refreshShadow(repositoryShadow, refreshOpts, task, parentResult);
if (refreshShadowOperation != null) {
repositoryShadow = refreshShadowOperation.getRefreshedShadow();
}
LOGGER.trace("Refreshed repository shadow:\n{}", DebugUtil.debugDumpLazily(repositoryShadow,1));
}
if (repositoryShadow == null) {
// Dead shadow was just removed
// TODO: is this OK? What about re-appeared objects
LOGGER.warn("DEAD shadow {} DEAD?", oid);
ObjectNotFoundException e = new ObjectNotFoundException("Resource object does not exist");
parentResult.recordFatalError(e);
throw e;
}
ShadowState shadowState = shadowCaretaker.determineShadowState(ctx, repositoryShadow, now);
LOGGER.trace("State of shadow {}: {}", repositoryShadow, shadowState);
if (canImmediatelyReturnCached(options, repositoryShadow, shadowState, resource)) {
LOGGER.trace("Returning cached (repository) version of shadow {}", repositoryShadow);
PrismObject<ShadowType> resultShadow = futurizeShadow(ctx, repositoryShadow, null, options, now);
shadowCaretaker.applyAttributesDefinition(ctx, resultShadow);
validateShadow(resultShadow, true);
return resultShadow;
}
PrismObject<ShadowType> resourceObject;
if (identifiersOverride == null) {
Collection<? extends ResourceAttribute<?>> primaryIdentifiers = ShadowUtil.getPrimaryIdentifiers(repositoryShadow);
if (primaryIdentifiers == null || primaryIdentifiers.isEmpty()) {
if (ProvisioningUtil.hasPendingAddOperation(repositoryShadow) || ShadowUtil
.isDead(repositoryShadow.asObjectable())) {
if (ProvisioningUtil.isFuturePointInTime(options)) {
// Get of uncreated or dead shadow, we want to see future state (how the shadow WILL look like).
// We cannot even try fetch operation here. We do not have the identifiers.
// But we have quite a good idea how the shadow is going to look like. Therefore we can return it.
PrismObject<ShadowType> resultShadow = futurizeShadow(ctx, repositoryShadow, null, options, now);
shadowCaretaker.applyAttributesDefinition(ctx, resultShadow);
validateShadow(resultShadow, true);
// NOTE: do NOT re-try add operation here. It will be retried in separate task.
// re-trying the operation here would not provide big benefits and it will complicate the code.
return resultShadow;
} else {
// Get of uncreated shadow, but we want current state. Therefore we have to throw an error because
// the object does not exist yet - to our best knowledge. But we cannot really throw ObjectNotFound here.
// ObjectNotFound is a positive indication that the object does not exist.
// We do not know that for sure because resource is unavailable. The object might have been created in the meantime.
throw new GenericConnectorException(
"Unable to get object from the resource. Probably it has not been created yet because of previous unavailability of the resource.");
}
}
// No identifiers found
SchemaException ex = new SchemaException("No primary identifiers found in the repository shadow "
+ repositoryShadow + " with respect to " + resource);
parentResult.recordFatalError("No primary identifiers found in the repository shadow " + repositoryShadow, ex);
throw ex;
}
}
Collection<? extends ResourceAttribute<?>> identifiers = identifiersOverride != null ? identifiersOverride :
ShadowUtil.getAllIdentifiers(repositoryShadow);
try {
try {
resourceObject = resourceObjectConverter.getResourceObject(ctx, identifiers, true, parentResult);
} catch (ObjectNotFoundException e) {
// This may be OK, e.g. for connectors that have running async add operation.
if (shadowState == ShadowState.CONCEPTION || shadowState == ShadowState.GESTATION) {
LOGGER.trace("{} was not found, but we can return cached shadow because it is in {} state", repositoryShadow, shadowState);
parentResult.deleteLastSubresultIfError(); // we don't want to see 'warning-like' orange boxes in GUI (TODO reconsider this)
parentResult.recordSuccess();
PrismObject<ShadowType> resultShadow = futurizeShadow(ctx, repositoryShadow, null, options, now);
shadowCaretaker.applyAttributesDefinition(ctx, resultShadow);
LOGGER.trace("Returning futurized shadow:\n{}", DebugUtil.debugDumpLazily(resultShadow));
validateShadow(resultShadow, true);
return resultShadow;
} else {
LOGGER.trace("{} was not found, following normal error processing because shadow is in {} state", repositoryShadow, shadowState);
// This is live shadow that was not found on resource. Just re-throw the exception. It will
// be caught later and the usual error handlers will bury the shadow.
throw e;
}
}
LOGGER.trace("Shadow returned by ResourceObjectConverter:\n{}", resourceObject.debugDumpLazily(1));
// Resource shadow may have different auxiliary object classes than
// the original repo shadow. Make sure we have the definition that
// applies to resource shadow. We will fix repo shadow later.
// BUT we need also information about kind/intent and these information is only
// in repo shadow, therefore the following 2 lines..
resourceObject.asObjectable().setKind(repositoryShadow.asObjectable().getKind());
resourceObject.asObjectable().setIntent(repositoryShadow.asObjectable().getIntent());
ProvisioningContext shadowCtx = ctx.spawn(resourceObject);
resourceManager.modifyResourceAvailabilityStatus(resource.getOid(), AvailabilityStatusType.UP, false, task, parentResult);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Shadow from repository:\n{}", repositoryShadow.debugDump(1));
LOGGER.trace("Resource object fetched from resource:\n{}", resourceObject.debugDump(1));
}
repositoryShadow = shadowManager.updateShadow(shadowCtx, resourceObject, null, repositoryShadow, shadowState, parentResult);
LOGGER.trace("Repository shadow after update:\n{}", repositoryShadow.debugDumpLazily(1));
// Complete the shadow by adding attributes from the resource object
// This also completes the associations by adding shadowRefs
PrismObject<ShadowType> assembledShadow = completeShadow(shadowCtx, resourceObject, repositoryShadow, false, parentResult);
LOGGER.trace("Shadow when assembled:\n{}", assembledShadow.debugDumpLazily(1));
PrismObject<ShadowType> resultShadow = futurizeShadow(ctx, repositoryShadow, assembledShadow, options, now);
LOGGER.trace("Futurized assembled shadow:\n{}", resultShadow.debugDumpLazily(1));
parentResult.recordSuccess();
validateShadow(resultShadow, true);
return resultShadow;
} catch (Exception ex) {
try {
PrismObject<ShadowType> handledShadow = handleGetError(ctx, repositoryShadow, rootOptions, ex, task, parentResult);
if (handledShadow == null) {
throw ex;
}
if (parentResult.getStatus() == OperationResultStatus.FATAL_ERROR) {
// We are going to return an object. Therefore this cannot
// be fatal error, as at least some information
// is returned
parentResult.setStatus(OperationResultStatus.PARTIAL_ERROR);
}
PrismObject<ShadowType> futurizedShadow = futurizeShadow(ctx, handledShadow, null, options, now);
validateShadow(futurizedShadow, true);
return futurizedShadow;
} catch (GenericFrameworkException | ObjectAlreadyExistsException | PolicyViolationException e) {
throw new SystemException(e.getMessage(), e);
}
} finally {
// We need to record the fetch down here. Now it is certain that we
// are going to fetch from resource (we do not have raw/noFetch option)
InternalMonitor.recordCount(InternalCounters.SHADOW_FETCH_OPERATION_COUNT);
}
}
private ProvisioningOperationOptions toProvisioningOperationOptions(GetOperationOptions getOpts) {
if (getOpts == null) {
return null;
}
ProvisioningOperationOptions provisioningOpts = new ProvisioningOperationOptions();
// for now, we are interested in forceRetry option. In the future, there can be more.
provisioningOpts.setForceRetry(getOpts.getForceRetry());
return provisioningOpts;
}
private boolean shouldRefreshOnRead(ResourceType resource, GetOperationOptions rootOptions) {
return GetOperationOptions.isForceRefresh(rootOptions) || GetOperationOptions.isForceRetry(rootOptions) || ResourceTypeUtil.isRefreshOnRead(resource);
}
private PrismObject<ShadowType> processNoFetchGet(ProvisioningContext ctx,
PrismObject<ShadowType> repositoryShadow, Collection<SelectorOptions<GetOperationOptions>> options,
XMLGregorianCalendar now, Task task, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException, EncryptionException {
LOGGER.trace("Processing noFetch get for {}", repositoryShadow);
GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options);
if (!GetOperationOptions.isRaw(rootOptions)) {
// Even with noFetch we still want to delete expired pending operations. And even delete
// the shadow if needed.
repositoryShadow = refreshShadowQuick(ctx, repositoryShadow, now, task, parentResult);
}
if (repositoryShadow == null) {
ObjectNotFoundException e = new ObjectNotFoundException("Resource object not found");
parentResult.recordFatalError(e);
throw e;
}
PrismObject<ShadowType> resultShadow = futurizeShadow(ctx, repositoryShadow, null, options, now);
shadowCaretaker.applyAttributesDefinition(ctx, resultShadow);
return resultShadow;
}
private PrismObject<ShadowType> futurizeShadow(ProvisioningContext ctx, PrismObject<ShadowType> repoShadow, PrismObject<ShadowType> resourceShadow,
Collection<SelectorOptions<GetOperationOptions>> options, XMLGregorianCalendar now) throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, ExpressionEvaluationException {
if (!ProvisioningUtil.isFuturePointInTime(options)) {
if (resourceShadow == null) {
return repoShadow;
} else {
return resourceShadow;
}
}
return shadowCaretaker.applyPendingOperations(ctx, repoShadow, resourceShadow, false, now);
}
private boolean canReturnCachedAfterObjectNotFound(Collection<SelectorOptions<GetOperationOptions>> options,
PrismObject<ShadowType> repositoryShadow, ResourceType resource) {
if (repositoryShadow.asObjectable().getPendingOperation().isEmpty()) {
return false;
}
// TODO: which case is this exactly?
// Explicitly check the capability of the resource (primary connector), not capabilities of additional connectors
return ProvisioningUtil.isPrimaryCachingOnly(resource);
}
private boolean canImmediatelyReturnCached(Collection<SelectorOptions<GetOperationOptions>> options, PrismObject<ShadowType> repositoryShadow, ShadowState shadowState, ResourceType resource) throws ConfigurationException {
if (ProvisioningUtil.resourceReadIsCachingOnly(resource)) {
return true;
}
if (shadowState == ShadowState.TOMBSTONE) {
// Once shadow is buried it stays nine feet under. Therefore there is no point in trying to access the resource.
// NOTE: this is just for tombstone! Schroedinger's shadows (corpse) will still work as if they were alive.
return true;
}
long stalenessOption = GetOperationOptions.getStaleness(SelectorOptions.findRootOptions(options));
PointInTimeType pit = GetOperationOptions.getPointInTimeType(SelectorOptions.findRootOptions(options));
if (pit == null) {
if (stalenessOption > 0) {
pit = PointInTimeType.CACHED;
} else {
pit = PointInTimeType.CURRENT;
}
}
switch (pit) {
case CURRENT:
// We need current reliable state. Never return cached data.
return false;
case CACHED:
return isCachedShadowValid(options, repositoryShadow, resource);
case FUTURE:
// We could, e.g. if there is a pending create operation. But let's try real get operation first.
return false;
default:
throw new IllegalArgumentException("Unknown point in time: "+pit);
}
}
private boolean isCachedShadowValid(Collection<SelectorOptions<GetOperationOptions>> options, PrismObject<ShadowType> repositoryShadow, ResourceType resource) throws ConfigurationException {
long stalenessOption = GetOperationOptions.getStaleness(SelectorOptions.findRootOptions(options));
if (stalenessOption == 0L) {
return false;
}
CachingMetadataType cachingMetadata = repositoryShadow.asObjectable().getCachingMetadata();
if (cachingMetadata == null) {
if (stalenessOption == Long.MAX_VALUE) {
// We must return cached version but there is no cached version.
throw new ConfigurationException("Cached version of "+repositoryShadow+" requested, but there is no cached value");
}
return false;
}
if (stalenessOption == Long.MAX_VALUE) {
return true;
}
XMLGregorianCalendar retrievalTimestamp = cachingMetadata.getRetrievalTimestamp();
if (retrievalTimestamp == null) {
return false;
}
long retrievalTimestampMillis = XmlTypeConverter.toMillis(retrievalTimestamp);
return (clock.currentTimeMillis() - retrievalTimestampMillis < stalenessOption);
}
private boolean isCompensate(GetOperationOptions rootOptions) {
return !GetOperationOptions.isDoNotDiscovery(rootOptions);
}
public String addShadow(PrismObject<ShadowType> shadowToAdd, OperationProvisioningScriptsType scripts,
ResourceType resource, ProvisioningOperationOptions options, Task task,
OperationResult parentResult) throws CommunicationException, GenericFrameworkException,
ObjectAlreadyExistsException, SchemaException, ObjectNotFoundException,
ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException, EncryptionException {
Validate.notNull(shadowToAdd, "Object to add must not be null.");
InternalMonitor.recordCount(InternalCounters.SHADOW_CHANGE_OPERATION_COUNT);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Start adding shadow object{}:\n{}", getAdditionalOperationDesc(scripts, options), shadowToAdd.debugDump(1));
}
ProvisioningContext ctx = ctxFactory.create(shadowToAdd, task, parentResult);
try {
ctx.assertDefinition();
} catch (SchemaException e) {
parentResult.recordFatalError(e);
ResourceOperationDescription operationDescription = ProvisioningUtil.createResourceFailureDescription(
shadowToAdd, ctx.getResource(), shadowToAdd.createAddDelta(), parentResult);
operationListener.notifyFailure(operationDescription, task, parentResult);
throw e;
}
ProvisioningOperationState<AsynchronousOperationReturnValue<PrismObject<ShadowType>>> opState = new ProvisioningOperationState<>();
return addShadowAttempt(ctx, shadowToAdd, scripts, opState, options, task, parentResult);
}
private String addShadowAttempt(ProvisioningContext ctx,
PrismObject<ShadowType> shadowToAdd,
OperationProvisioningScriptsType scripts,
ProvisioningOperationState<AsynchronousOperationReturnValue<PrismObject<ShadowType>>> opState,
ProvisioningOperationOptions options,
Task task,
OperationResult parentResult)
throws CommunicationException, GenericFrameworkException,
ObjectAlreadyExistsException, SchemaException, ObjectNotFoundException,
ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException, EncryptionException {
PrismContainer<?> attributesContainer = shadowToAdd.findContainer(ShadowType.F_ATTRIBUTES);
if (attributesContainer == null || attributesContainer.isEmpty()) {
SchemaException e = new SchemaException("Attempt to add shadow without any attributes: " + shadowToAdd);
parentResult.recordFatalError(e);
ResourceOperationDescription operationDescription = ProvisioningUtil.createResourceFailureDescription(
shadowToAdd, ctx.getResource(), shadowToAdd.createAddDelta(), parentResult);
operationListener.notifyFailure(operationDescription, task, parentResult);
throw e;
}
if (!(attributesContainer instanceof ResourceAttributeContainer)) {
shadowCaretaker.applyAttributesDefinition(ctx, shadowToAdd);
attributesContainer = shadowToAdd.findContainer(ShadowType.F_ATTRIBUTES);
}
// if (opState.getRepoShadow() != null) {
// // HACK HACK HACK, not really right solution.
// // We need this for reliable uniqueness check in preAddChecks() and addResourceObject()
// // Maybe the right solution would be to pass opState as a parameter to addResourceObject()?
// // Or maybe addResourceObject() should not check uniqueness and we shoudl check it here?
// shadowToAdd.setOid(opState.getRepoShadow().getOid());
// }
preAddChecks(ctx, shadowToAdd, opState, task, parentResult);
shadowManager.addNewProposedShadow(ctx, shadowToAdd, opState, task, parentResult);
preprocessEntitlements(ctx, shadowToAdd, parentResult);
shadowCaretaker.applyAttributesDefinition(ctx, shadowToAdd);
shadowManager.setKindIfNecessary(shadowToAdd.asObjectable(), ctx.getObjectClassDefinition());
accessChecker.checkAdd(ctx, shadowToAdd, parentResult);
PrismObject<ShadowType> addedShadow = null;
OperationResultStatus finalOperationStatus = null;
if (shouldExecuteResourceOperationDirectly(ctx)) {
ConnectorOperationOptions connOptions = createConnectorOperationOptions(ctx, options, parentResult);
LOGGER.trace("ADD {}: resource operation, execution starting", shadowToAdd);
try {
// RESOURCE OPERATION: add
AsynchronousOperationReturnValue<PrismObject<ShadowType>> asyncReturnValue =
resourceObjectConverter.addResourceObject(ctx, shadowToAdd, scripts, connOptions, false, parentResult);
opState.processAsyncResult(asyncReturnValue);
addedShadow = asyncReturnValue.getReturnValue();
} catch (ObjectAlreadyExistsException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Object already exists error when trying to add {}, exploring the situation", ShadowUtil.shortDumpShadow(shadowToAdd));
}
// This exception may still be OK in some cases. Such as:
// We are trying to add a shadow to a semi-manual connector.
// But the resource object was recently deleted. The object is
// still in the backing store (CSV file) because of a grace
// period. Obviously, attempt to add such object would fail.
// So, we need to handle this case specially. (MID-4414)
OperationResult failedOperationResult = parentResult.getLastSubresult();
if (hasDeadShadowWithDeleteOperation(ctx, shadowToAdd, parentResult)) {
if (failedOperationResult.isError()) {
failedOperationResult.setStatus(OperationResultStatus.HANDLED_ERROR);
}
// Try again, this time without explicit uniqueness check
try {
LOGGER.trace("ADD {}: retrying resource operation without uniqueness check (previous dead shadow found), execution starting", shadowToAdd);
AsynchronousOperationReturnValue<PrismObject<ShadowType>> asyncReturnValue =
resourceObjectConverter
.addResourceObject(ctx, shadowToAdd, scripts, connOptions, true, parentResult);
opState.processAsyncResult(asyncReturnValue);
addedShadow = asyncReturnValue.getReturnValue();
} catch (ObjectAlreadyExistsException innerException) {
// Mark shadow dead before we handle the error. ADD operation obviously failed. Therefore this particular
// shadow was not created as resource object. It is dead on the spot. Make sure that error handler won't confuse
// this shadow with the conflicting shadow that it is going to discover.
// This may also be a gestation quantum state collapsing to tombstone
shadowManager.markShadowTombstone(opState.getRepoShadow(), parentResult);
finalOperationStatus = handleAddError(ctx, shadowToAdd, options, opState, innerException, failedOperationResult, task, parentResult);
} catch (Exception innerException) {
finalOperationStatus = handleAddError(ctx, shadowToAdd, options, opState, innerException, parentResult.getLastSubresult(), task, parentResult);
}
} else {
// Mark shadow dead before we handle the error. ADD operation obviously failed. Therefore this particular
// shadow was not created as resource object. It is dead on the spot. Make sure that error handler won't confuse
// this shadow with the conflicting shadow that it is going to discover.
// This may also be a gestation quantum state collapsing to tombstone
shadowManager.markShadowTombstone(opState.getRepoShadow(), parentResult);
finalOperationStatus = handleAddError(ctx, shadowToAdd, options, opState, e, failedOperationResult, task, parentResult);
}
} catch (Exception e) {
finalOperationStatus = handleAddError(ctx, shadowToAdd, options, opState, e, parentResult.getLastSubresult(), task, parentResult);
}
LOGGER.debug("ADD {}: resource operation executed, operation state: {}", shadowToAdd, opState.shortDumpLazily());
} else {
opState.setExecutionStatus(PendingOperationExecutionStatusType.EXECUTION_PENDING);
// Create dummy subresult with IN_PROGRESS state.
// This will force the entire result (parent) to be IN_PROGRESS rather than SUCCESS.
OperationResult delayedSubresult = parentResult.createSubresult(OP_DELAYED_OPERATION);
delayedSubresult.setStatus(OperationResultStatus.IN_PROGRESS);
LOGGER.debug("ADD {}: resource operation NOT executed, execution pending", shadowToAdd);
}
// REPO OPERATION: add
// This is where the repo shadow is created or updated (if needed)
shadowManager.recordAddResult(ctx, shadowToAdd, opState, parentResult);
if (addedShadow == null) {
addedShadow = shadowToAdd;
}
addedShadow.setOid(opState.getRepoShadow().getOid());
notifyAfterAdd(ctx, addedShadow, opState, task, parentResult);
setParentOperationStatus(parentResult, opState, finalOperationStatus);
return opState.getRepoShadow().getOid();
}
private void setParentOperationStatus(OperationResult parentResult,
ProvisioningOperationState<? extends AsynchronousOperationResult> opState,
OperationResultStatus finalOperationStatus) {
if (finalOperationStatus != null) {
parentResult.setStatus(finalOperationStatus);
} else {
if (opState.isCompleted()) {
parentResult.computeStatus();
} else {
parentResult.recordInProgress();
}
}
parentResult.setAsynchronousOperationReference(opState.getAsynchronousOperationReference());
}
private boolean hasDeadShadowWithDeleteOperation(ProvisioningContext ctx,
PrismObject<ShadowType> shadowToAdd,
OperationResult parentResult)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
Collection<PrismObject<ShadowType>> previousDeadShadows = shadowManager.lookForPreviousDeadShadows(ctx, shadowToAdd, parentResult);
if (previousDeadShadows.isEmpty()) {
return false;
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Previous dead shadows:\n{}", DebugUtil.debugDump(previousDeadShadows, 1));
}
XMLGregorianCalendar now = clock.currentTimeXMLGregorianCalendar();
for (PrismObject<ShadowType> previousDeadShadow : previousDeadShadows) {
if (shadowCaretaker.findPreviousPendingLifecycleOperationInGracePeriod(ctx, previousDeadShadow, now) == ChangeTypeType.DELETE) {
return true;
}
}
return false;
}
private PrismObject<ShadowType> handleGetError(ProvisioningContext ctx,
PrismObject<ShadowType> repositoryShadow,
GetOperationOptions rootOptions,
Exception cause,
Task task,
OperationResult parentResult) throws SchemaException, GenericFrameworkException, CommunicationException, ObjectNotFoundException, ObjectAlreadyExistsException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException {
ErrorHandler handler = errorHandlerLocator.locateErrorHandler(cause);
if (handler == null) {
parentResult.recordFatalError("Error without a handler: " + cause.getMessage(), cause);
throw new SystemException(cause.getMessage(), cause);
}
LOGGER.debug("Handling provisioning GET exception {}: {}", cause.getClass(), cause.getMessage());
return handler.handleGetError(ctx, repositoryShadow, rootOptions, cause, task, parentResult);
}
private OperationResultStatus handleAddError(ProvisioningContext ctx,
PrismObject<ShadowType> shadowToAdd,
ProvisioningOperationOptions options,
ProvisioningOperationState<AsynchronousOperationReturnValue<PrismObject<ShadowType>>> opState,
Exception cause,
OperationResult failedOperationResult,
Task task,
OperationResult parentResult)
throws SchemaException, GenericFrameworkException, CommunicationException, ObjectNotFoundException, ObjectAlreadyExistsException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException {
// TODO: record operationExecution
ErrorHandler handler = errorHandlerLocator.locateErrorHandler(cause);
if (handler == null) {
parentResult.recordFatalError("Error without a handler: " + cause.getMessage(), cause);
throw new SystemException(cause.getMessage(), cause);
}
LOGGER.debug("Handling provisioning ADD exception {}: {}", cause.getClass(), cause.getMessage());
try {
OperationResultStatus finalStatus = handler.handleAddError(ctx, shadowToAdd, options, opState, cause, failedOperationResult, task, parentResult);
LOGGER.debug("Handled provisioning ADD exception, final status: {}, operation state: {}", finalStatus, opState.shortDumpLazily());
return finalStatus;
} catch (CommonException e) {
LOGGER.debug("Handled provisioning ADD exception, final exception: {}, operation state: {}", e, opState.shortDumpLazily());
ObjectDelta<ShadowType> delta = shadowToAdd.createAddDelta();
handleErrorHandlerException(ctx, opState, delta, task, parentResult);
throw e;
}
}
private void handleErrorHandlerException(ProvisioningContext ctx,
ProvisioningOperationState<? extends AsynchronousOperationResult> opState,
ObjectDelta<ShadowType> delta,
Task task, OperationResult parentResult) throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, ObjectAlreadyExistsException, ExpressionEvaluationException {
// Error handler had re-thrown the exception. We will throw the exception later. But first we need to record changes in opState.
shadowManager.recordOperationException(ctx, opState, delta, parentResult);
PrismObject<ShadowType> shadow = opState.getRepoShadow();
if (delta.isAdd()) {
// This is more precise. Besides, there is no repo shadow in some cases (e.g. adding protected shadow).
shadow = delta.getObjectToAdd();
}
ResourceOperationDescription operationDescription = ProvisioningUtil.createResourceFailureDescription(shadow, ctx.getResource(), delta, parentResult);
operationListener.notifyFailure(operationDescription, task, parentResult);
}
private OperationResultStatus handleModifyError(ProvisioningContext ctx,
PrismObject<ShadowType> repoShadow,
Collection<? extends ItemDelta> modifications,
ProvisioningOperationOptions options,
ProvisioningOperationState<AsynchronousOperationReturnValue<Collection<PropertyDelta<PrismPropertyValue>>>> opState,
Exception cause,
OperationResult failedOperationResult,
Task task,
OperationResult parentResult)
throws SchemaException, GenericFrameworkException, CommunicationException, ObjectNotFoundException, ObjectAlreadyExistsException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException {
// TODO: record operationExecution
ErrorHandler handler = errorHandlerLocator.locateErrorHandler(cause);
if (handler == null) {
parentResult.recordFatalError("Error without a handler: " + cause.getMessage(), cause);
throw new SystemException(cause.getMessage(), cause);
}
LOGGER.debug("Handling provisioning MODIFY exception {}: {}", cause.getClass(), cause.getMessage());
try {
OperationResultStatus finalStatus = handler.handleModifyError(ctx, repoShadow, modifications, options, opState, cause, failedOperationResult, task, parentResult);
LOGGER.debug("Handled provisioning MODIFY exception, final status: {}, operation state: {}", finalStatus, opState.shortDumpLazily());
return finalStatus;
} catch (CommonException e) {
LOGGER.debug("Handled provisioning MODIFY exception, final exception: {}, operation state: {}", e, opState.shortDumpLazily());
ObjectDelta<ShadowType> delta = repoShadow.createModifyDelta();
delta.addModifications(modifications);
handleErrorHandlerException(ctx, opState, delta, task, parentResult);
throw e;
}
}
private OperationResultStatus handleDeleteError(ProvisioningContext ctx,
PrismObject<ShadowType> repoShadow,
ProvisioningOperationOptions options,
ProvisioningOperationState<AsynchronousOperationResult> opState,
Exception cause,
OperationResult failedOperationResult,
Task task,
OperationResult parentResult)
throws SchemaException, GenericFrameworkException, CommunicationException, ObjectNotFoundException, ObjectAlreadyExistsException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException {
ErrorHandler handler = errorHandlerLocator.locateErrorHandler(cause);
if (handler == null) {
parentResult.recordFatalError("Error without a handler: " + cause.getMessage(), cause);
throw new SystemException(cause.getMessage(), cause);
}
LOGGER.debug("Handling provisioning DELETE exception {}: {}", cause.getClass(), cause.getMessage());
try {
OperationResultStatus finalStatus = handler.handleDeleteError(ctx, repoShadow, options, opState, cause, failedOperationResult, task, parentResult);
LOGGER.debug("Handled provisioning DELETE exception, final status: {}, operation state: {}", finalStatus, opState.shortDumpLazily());
return finalStatus;
} catch (CommonException e) {
LOGGER.debug("Handled provisioning DELETE exception, final exception: {}, operation state: {}", e, opState.shortDumpLazily());
ObjectDelta<ShadowType> delta = repoShadow.createDeleteDelta();
handleErrorHandlerException(ctx, opState, delta, task, parentResult);
throw e;
}
}
private void notifyAfterAdd(
ProvisioningContext ctx,
PrismObject<ShadowType> addedShadow,
ProvisioningOperationState<AsynchronousOperationReturnValue<PrismObject<ShadowType>>> opState,
Task task,
OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
ObjectDelta<ShadowType> delta = DeltaFactory.Object.createAddDelta(addedShadow);
ResourceOperationDescription operationDescription = createSuccessOperationDescription(ctx, addedShadow,
delta, parentResult);
if (opState.isExecuting()) {
operationListener.notifyInProgress(operationDescription, task, parentResult);
} else if (opState.isCompleted()) {
operationListener.notifySuccess(operationDescription, task, parentResult);
}
}
private void preAddChecks(ProvisioningContext ctx, PrismObject<ShadowType> shadow, ProvisioningOperationState<AsynchronousOperationReturnValue<PrismObject<ShadowType>>> opState, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException, ObjectAlreadyExistsException, SecurityViolationException {
checkConstraints(ctx, shadow, opState, task, result);
validateSchema(ctx, shadow, task, result);
}
private void checkConstraints(ProvisioningContext ctx, PrismObject<ShadowType> shadow, ProvisioningOperationState<AsynchronousOperationReturnValue<PrismObject<ShadowType>>> opState, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException, ObjectAlreadyExistsException, SecurityViolationException {
ShadowCheckType shadowConstraintsCheck = ResourceTypeUtil.getShadowConstraintsCheck(ctx.getResource());
if (shadowConstraintsCheck == ShadowCheckType.NONE) {
return;
}
String shadowOid = shadow.getOid();
if (opState.getRepoShadow() != null) {
shadowOid = opState.getRepoShadow().getOid();
}
ConstraintsChecker checker = new ConstraintsChecker();
checker.setRepositoryService(repositoryService);
checker.setCacheConfigurationManager(cacheConfigurationManager);
checker.setShadowCache(this);
checker.setPrismContext(prismContext);
checker.setProvisioningContext(ctx);
checker.setShadowObject(shadow);
checker.setShadowOid(shadowOid);
checker.setConstraintViolationConfirmer(conflictingShadowCandidate -> !Boolean.TRUE.equals(conflictingShadowCandidate.asObjectable().isDead()) );
checker.setUseCache(false);
ConstraintsCheckingResult retval = checker.check(task, result);
LOGGER.trace("Checked {} constraints, result={}", shadow.debugDump(), retval.isSatisfiesConstraints());
if (!retval.isSatisfiesConstraints()) {
throw new ObjectAlreadyExistsException("Conflicting shadow already exists on "+ctx.getResource());
}
}
private void validateSchema(ProvisioningContext ctx, PrismObject<ShadowType> shadow, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
if (ResourceTypeUtil.isValidateSchema(ctx.getResource())) {
ShadowUtil.validateAttributeSchema(shadow, ctx.getObjectClassDefinition());
}
}
private boolean shouldExecuteResourceOperationDirectly(ProvisioningContext ctx) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
if (ctx.isPropagation()) {
return true;
}
ResourceConsistencyType consistency = ctx.getResource().getConsistency();
if (consistency == null) {
return true;
}
Duration operationGroupingInterval = consistency.getOperationGroupingInterval();
if (operationGroupingInterval == null) {
return true;
}
return false;
}
private ResourceOperationDescription createSuccessOperationDescription(ProvisioningContext ctx,
PrismObject<ShadowType> shadowType, ObjectDelta delta, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, CommunicationException,
ConfigurationException, ExpressionEvaluationException {
ResourceOperationDescription operationDescription = new ResourceOperationDescription();
operationDescription.setCurrentShadow(shadowType);
operationDescription.setResource(ctx.getResource().asPrismObject());
if (ctx.getTask() != null) {
operationDescription.setSourceChannel(ctx.getTask().getChannel());
}
operationDescription.setObjectDelta(delta);
operationDescription.setResult(parentResult);
return operationDescription;
}
public String modifyShadow(PrismObject<ShadowType> repoShadow,
Collection<? extends ItemDelta> modifications, OperationProvisioningScriptsType scripts,
ProvisioningOperationOptions options, Task task, OperationResult parentResult)
throws CommunicationException, GenericFrameworkException, ObjectNotFoundException,
SchemaException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException, EncryptionException, ObjectAlreadyExistsException {
Validate.notNull(repoShadow, "Object to modify must not be null.");
Validate.notNull(modifications, "Object modification must not be null.");
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Start modifying {}{}:\n{}", repoShadow, getAdditionalOperationDesc(scripts, options),
DebugUtil.debugDump(modifications, 1));
}
InternalMonitor.recordCount(InternalCounters.SHADOW_CHANGE_OPERATION_COUNT);
Collection<QName> additionalAuxiliaryObjectClassQNames = new ArrayList<>();
for (ItemDelta modification : modifications) {
if (ShadowType.F_AUXILIARY_OBJECT_CLASS.equivalent(modification.getPath())) {
PropertyDelta<QName> auxDelta = (PropertyDelta<QName>) modification;
for (PrismPropertyValue<QName> pval : auxDelta.getValues(QName.class)) {
additionalAuxiliaryObjectClassQNames.add(pval.getValue());
}
}
}
ProvisioningContext ctx = ctxFactory.create(repoShadow, additionalAuxiliaryObjectClassQNames, task, parentResult);
ctx.assertDefinition();
ProvisioningOperationState<AsynchronousOperationReturnValue<Collection<PropertyDelta<PrismPropertyValue>>>> opState = new ProvisioningOperationState<>();
opState.setRepoShadow(repoShadow);
// if not explicitly we want to force retry operations during modify
// it is quite cheap and probably more safe then not do it
if (options == null) {
options = ProvisioningOperationOptions.createForceRetry(Boolean.TRUE);
} else if (options.getForceRetry() == null) {
options.setForceRetry(Boolean.TRUE);
}
return modifyShadowAttempt(ctx, modifications, scripts, options, opState, task, parentResult);
}
private String modifyShadowAttempt(ProvisioningContext ctx,
Collection<? extends ItemDelta> modifications,
OperationProvisioningScriptsType scripts,
ProvisioningOperationOptions options,
ProvisioningOperationState<AsynchronousOperationReturnValue<Collection<PropertyDelta<PrismPropertyValue>>>> opState,
Task task, OperationResult parentResult)
throws CommunicationException, GenericFrameworkException, ObjectNotFoundException,
SchemaException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException, EncryptionException, ObjectAlreadyExistsException {
PrismObject<ShadowType> repoShadow = opState.getRepoShadow();
XMLGregorianCalendar now = clock.currentTimeXMLGregorianCalendar();
PendingOperationType duplicateOperation = shadowManager.checkAndRecordPendingModifyOperationBeforeExecution(ctx, repoShadow, modifications, opState, task, parentResult);
if (duplicateOperation != null) {
parentResult.recordInProgress();
return repoShadow.getOid();
}
shadowCaretaker.applyAttributesDefinition(ctx, repoShadow);
accessChecker.checkModify(ctx, repoShadow, modifications, parentResult);
preprocessEntitlements(ctx, modifications, "delta for shadow " + repoShadow.getOid(), parentResult);
OperationResultStatus finalOperationStatus = null;
if (shadowManager.isRepositoryOnlyModification(modifications)) {
opState.setExecutionStatus(PendingOperationExecutionStatusType.COMPLETED);
LOGGER.debug("MODIFY {}: repository-only modification", repoShadow);
} else {
if (shouldExecuteResourceOperationDirectly(ctx)) {
LOGGER.trace("MODIFY {}: resource modification, execution starting\n{}", repoShadow, DebugUtil.debugDumpLazily(modifications));
RefreshShadowOperation refreshShadowOperation = null;
if (shouldRefresh(repoShadow)) {
refreshShadowOperation = refreshShadow(repoShadow, options, task, parentResult);
}
if (refreshShadowOperation != null) {
repoShadow = refreshShadowOperation.getRefreshedShadow();
}
if (repoShadow == null) {
LOGGER.trace("Shadow is gone. Nothing more to do");
parentResult.recordPartialError("Shadow disappeared during modify.");
throw new ObjectNotFoundException("Shadow is gone.");
}
ConnectorOperationOptions connOptions = createConnectorOperationOptions(ctx, options, parentResult);
try {
if (!shouldExecuteModify(refreshShadowOperation)) {
ProvisioningUtil.postponeModify(ctx, repoShadow, modifications, opState, refreshShadowOperation.getRefreshResult(), parentResult);
shadowManager.recordModifyResult(ctx, repoShadow, modifications, opState, now, parentResult);
return repoShadow.getOid();
} else {
LOGGER.trace("Shadow exists: {}", repoShadow.debugDump());
}
AsynchronousOperationReturnValue<Collection<PropertyDelta<PrismPropertyValue>>> asyncReturnValue =
resourceObjectConverter
.modifyResourceObject(ctx, repoShadow, scripts, connOptions, modifications, now, parentResult);
opState.processAsyncResult(asyncReturnValue);