/
ProvisioningServiceImpl.java
1417 lines (1175 loc) · 58.7 KB
/
ProvisioningServiceImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2010-2018 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.provisioning.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.xml.namespace.QName;
import com.evolveum.midpoint.prism.delta.ItemDeltaCollectionsUtil;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.repo.api.SystemConfigurationChangeDispatcher;
import com.evolveum.midpoint.repo.api.SystemConfigurationChangeListener;
import com.evolveum.midpoint.schema.cache.CacheConfigurationManager;
import com.evolveum.midpoint.schema.cache.CacheType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
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.context.annotation.Primary;
import org.springframework.stereotype.Service;
import com.evolveum.midpoint.common.crypto.CryptoUtil;
import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition;
import com.evolveum.midpoint.prism.Objectable;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismObjectDefinition;
import com.evolveum.midpoint.prism.PrismProperty;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.query.NoneFilter;
import com.evolveum.midpoint.prism.query.ObjectFilter;
import com.evolveum.midpoint.prism.query.ObjectPaging;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.provisioning.api.ConstraintViolationConfirmer;
import com.evolveum.midpoint.provisioning.api.ConstraintsCheckingResult;
import com.evolveum.midpoint.provisioning.api.GenericConnectorException;
import com.evolveum.midpoint.provisioning.api.ItemComparisonResult;
import com.evolveum.midpoint.provisioning.api.ProvisioningOperationOptions;
import com.evolveum.midpoint.provisioning.api.ProvisioningService;
import com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException;
import com.evolveum.midpoint.provisioning.util.ProvisioningUtil;
import com.evolveum.midpoint.repo.api.RepoAddOptions;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.LabeledString;
import com.evolveum.midpoint.schema.ProvisioningDiag;
import com.evolveum.midpoint.schema.ResourceShadowDiscriminator;
import com.evolveum.midpoint.schema.ResultHandler;
import com.evolveum.midpoint.schema.SearchResultList;
import com.evolveum.midpoint.schema.SearchResultMetadata;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.constants.ConnectorTestOperation;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.internals.InternalsConfig;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.statistics.ConnectorOperationalStatus;
import com.evolveum.midpoint.schema.util.ObjectQueryUtil;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.schema.util.SchemaDebugUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.PolicyViolationException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
/**
* Implementation of provisioning service.
*
* It is just a "dispatcher" that routes interface calls to appropriate places.
* E.g. the operations regarding resource definitions are routed directly to the
* repository, operations of shadow objects are routed to the shadow cache and
* so on.
*
* @author Radovan Semancik
*/
@Service(value = "provisioningService")
@Primary
public class ProvisioningServiceImpl implements ProvisioningService, SystemConfigurationChangeListener {
private static final String OPERATION_REFRESH_SHADOW = ProvisioningServiceImpl.class.getName() +".refreshShadow";
@Autowired ShadowCache shadowCache;
@Autowired ResourceManager resourceManager;
@Autowired ConnectorManager connectorManager;
@Autowired ProvisioningContextFactory ctxFactory;
@Autowired PrismContext prismContext;
@Autowired CacheConfigurationManager cacheConfigurationManager;
@Autowired private SystemConfigurationChangeDispatcher systemConfigurationChangeDispatcher;
@Autowired
@Qualifier("cacheRepositoryService")
private RepositoryService cacheRepositoryService;
private PrismObjectDefinition<ShadowType> resourceObjectShadowDefinition;
private SystemConfigurationType systemConfiguration;
private static final Trace LOGGER = TraceManager.getTrace(ProvisioningServiceImpl.class);
private static final String DETAILS_CONNECTOR_FRAMEWORK_VERSION = "ConnId framework version"; // TODO generalize
/**
* Get the value of repositoryService.
*
* @return the value of repositoryService
*/
public RepositoryService getCacheRepositoryService() {
return cacheRepositoryService;
}
/**
* Set the value of repositoryService
*
* Expected to be injected.
*
* @param repositoryService
* new value of repositoryService
*/
public void setCacheRepositoryService(RepositoryService repositoryService) {
this.cacheRepositoryService = repositoryService;
}
@SuppressWarnings("unchecked")
@Override
public <T extends ObjectType> PrismObject<T> getObject(Class<T> type, String oid,
Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult parentResult) throws ObjectNotFoundException,
CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
Validate.notNull(oid, "Oid of object to get must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
// Result type for this operation
OperationResult result = parentResult.createMinorSubresult(ProvisioningService.class.getName() + ".getObject");
result.addParam(OperationResult.PARAM_OID, oid);
result.addParam(OperationResult.PARAM_TYPE, type);
result.addArbitraryObjectCollectionAsParam("options", options);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options);
PrismObject<T> resultingObject;
if (ResourceType.class.isAssignableFrom(type)) {
if (GetOperationOptions.isRaw(rootOptions)) {
try {
resultingObject = (PrismObject<T>) cacheRepositoryService.getObject(ResourceType.class, oid, options, result);
} catch (ObjectNotFoundException|SchemaException ex) {
// catching an exception is important because otherwise the result is UNKNOWN
result.recordFatalError(ex);
throw ex;
}
try {
applyDefinition(resultingObject, task, result);
} catch (ObjectNotFoundException ex) {
// this is almost OK, we use raw for debug pages, so we want
// to return resource and it can be fixed
result.muteLastSubresultError();
ProvisioningUtil.logWarning(LOGGER, result,
"Bad connector reference defined for resource: " + ex.getMessage(), ex);
} catch (SchemaException ex) {
result.muteLastSubresultError();
ProvisioningUtil.logWarning(LOGGER, result, "Schema violation: " + ex.getMessage(), ex);
} catch (ConfigurationException ex) {
result.muteLastSubresultError();
ProvisioningUtil.logWarning(LOGGER, result, "Configuration problem: " + ex.getMessage(), ex);
}
} else {
// We need to handle resource specially. This is usually cached
// and we do not want to get the repository
// object if it is in the cache.
// Make sure that the object is complete, e.g. there is a
// (fresh)
// schema
try {
resultingObject = (PrismObject<T>) resourceManager.getResource(oid, SelectorOptions.findRootOptions(options), task, result);
} catch (ObjectNotFoundException ex) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Resource object not found", ex);
throw ex;
} catch (SchemaException ex) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Schema violation", ex);
throw ex;
} catch (CommunicationException ex) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Error communicating with resource", ex);
throw ex;
} catch (ConfigurationException ex) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Bad resource configuration", ex);
throw ex;
} catch (ExpressionEvaluationException ex) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Expression error", ex);
throw ex;
}
}
} else {
// Not resource
PrismObject<T> repositoryObject = getRepoObject(type, oid, options, result);
LOGGER.trace("Retrieved repository object:\n{}", repositoryObject.debugDumpLazily());
if (repositoryObject.canRepresent(ShadowType.class)) {
try {
resultingObject = (PrismObject<T>) shadowCache.getShadow(oid,
(PrismObject<ShadowType>) (repositoryObject), options, task, result);
} catch (ObjectNotFoundException e) {
if (!GetOperationOptions.isAllowNotFound(rootOptions)){
ProvisioningUtil.recordFatalError(LOGGER, result, "Error getting object OID=" + oid + ": " + e.getMessage(), e);
} else{
result.muteLastSubresultError();
result.computeStatus();
}
throw e;
} catch (CommunicationException | SchemaException | ConfigurationException | SecurityViolationException | RuntimeException | Error e) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Error getting object OID=" + oid + ": " + e.getMessage(), e);
throw e;
} catch (EncryptionException e){
ProvisioningUtil.recordFatalError(LOGGER, result, "Error getting object OID=" + oid + ": " + e.getMessage(), e);
throw new SystemException(e);
}
} else {
resultingObject = repositoryObject;
}
}
result.computeStatusIfUnknown();
if (!GetOperationOptions.isRaw(rootOptions)) {
resultingObject = resultingObject.cloneIfImmutable();
resultingObject.asObjectable().setFetchResult(result.createOperationResultType());
}
result.cleanupResult();
return resultingObject;
}
@Override
public <T extends ObjectType> String addObject(PrismObject<T> object, OperationProvisioningScriptsType scripts, ProvisioningOperationOptions options,
Task task, OperationResult parentResult) throws ObjectAlreadyExistsException, SchemaException, CommunicationException,
ObjectNotFoundException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException {
Validate.notNull(object, "Object to add must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
if (InternalsConfig.encryptionChecks) {
CryptoUtil.checkEncrypted(object);
}
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName() + ".addObject");
result.addParam("object", object);
result.addArbitraryObjectAsParam("scripts", scripts);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
String oid = null;
if (object.canRepresent(ShadowType.class)) {
try {
// calling shadow cache to add object
oid = shadowCache.addShadow((PrismObject<ShadowType>) object, scripts,
null, options, task, result);
LOGGER.trace("Added shadow object {}", oid);
// Status might be set already (e.g. by consistency mechanism)
result.computeStatusIfUnknown();
} catch (GenericFrameworkException ex) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't add object " + object + ". Reason: " + ex.getMessage(), ex);
throw new ConfigurationException(ex.getMessage(), ex);
} catch (ObjectAlreadyExistsException ex) {
result.computeStatus();
if (!result.isSuccess() && !result.isHandledError()) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't add object. Object already exist: " + ex.getMessage(), ex);
} else {
result.recordSuccess();
}
result.cleanupResult(ex);
throw new ObjectAlreadyExistsException("Couldn't add object. Object already exists: " + ex.getMessage(),
ex);
} catch (EncryptionException e) {
ProvisioningUtil.recordFatalError(LOGGER, result, null, e);
throw new SystemException(e.getMessage(), e);
} catch (SchemaException | ConfigurationException | SecurityViolationException | PolicyViolationException | ExpressionEvaluationException | RuntimeException | Error e) {
ProvisioningUtil.recordFatalError(LOGGER, result, null, e);
throw e;
}
} else {
RepoAddOptions addOptions = null;
if (ProvisioningOperationOptions.isOverwrite(options)){
addOptions = RepoAddOptions.createOverwrite();
}
try {
oid = cacheRepositoryService.addObject(object, addOptions, result);
} catch (Throwable t) {
result.recordFatalError(t);
throw t;
} finally {
result.computeStatusIfUnknown();
}
}
result.cleanupResult();
return oid;
}
@SuppressWarnings("rawtypes")
@Override
public int synchronize(ResourceShadowDiscriminator shadowCoordinates, Task task, TaskPartitionDefinitionType taskPartition, OperationResult parentResult) throws ObjectNotFoundException,
CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException, PolicyViolationException {
Validate.notNull(shadowCoordinates, "Coordinates oid must not be null.");
String resourceOid = shadowCoordinates.getResourceOid();
Validate.notNull(resourceOid, "Resource oid must not be null.");
Validate.notNull(task, "Task must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName() + ".synchronize");
result.addParam(OperationResult.PARAM_OID, resourceOid);
result.addParam(OperationResult.PARAM_TASK, task.toString());
SynchronizationOperationResult liveSyncResult;
try {
// Resolve resource
PrismObject<ResourceType> resource = getObject(ResourceType.class, resourceOid, null, task, result);
ResourceType resourceType = resource.asObjectable();
LOGGER.trace("Start synchronization of resource {} ", resourceType);
// getting token form task
PrismProperty tokenProperty = getTokenProperty(shadowCoordinates, task, result);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Got token property: {} from the task extension.", SchemaDebugUtil.prettyPrint(tokenProperty));
}
liveSyncResult = shadowCache.synchronize(shadowCoordinates, tokenProperty, task, taskPartition, result);
LOGGER.debug("Synchronization of {} done, token at start {}, result: {}", resource, tokenProperty, liveSyncResult);
} catch (ObjectNotFoundException | CommunicationException | SchemaException | SecurityViolationException | ConfigurationException | ExpressionEvaluationException | RuntimeException | Error e) {
ProvisioningUtil.recordFatalError(LOGGER, result, null, e);
result.summarize(true);
throw e;
} catch (ObjectAlreadyExistsException e) {
ProvisioningUtil.recordFatalError(LOGGER, result, null, e);
result.summarize(true);
throw new SystemException(e);
} catch (GenericFrameworkException e) {
ProvisioningUtil.recordFatalError(LOGGER, result,
"Synchronization error: generic connector framework error: " + e.getMessage(), e);
result.summarize(true);
throw new GenericConnectorException(e.getMessage(), e);
}
if (liveSyncResult.isHaltingErrorEncountered()) {
// TODO MID-5514
result.recordPartialError("Object could not be processed and 'retryLiveSyncErrors' is true");
} else if (liveSyncResult.getErrors() > 0) {
result.recordPartialError("Errors while processing: " + liveSyncResult.getErrors() + " out of " + liveSyncResult.getChangesProcessed());
} else {
result.recordSuccess();
}
result.cleanupResult();
return liveSyncResult.getChangesProcessed();
}
@Override
public String startListeningForAsyncUpdates(@NotNull ResourceShadowDiscriminator shadowCoordinates, @NotNull Task task,
@NotNull OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException,
ExpressionEvaluationException {
String resourceOid = shadowCoordinates.getResourceOid();
Validate.notNull(resourceOid, "Resource oid must not be null.");
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName() + ".startListeningForAsyncUpdates");
result.addParam(OperationResult.PARAM_OID, resourceOid);
result.addParam(OperationResult.PARAM_TASK, task.toString());
String listeningActivityHandle;
try {
LOGGER.trace("Starting listening for async updates for {}", shadowCoordinates);
listeningActivityHandle = shadowCache.startListeningForAsyncUpdates(shadowCoordinates, task, result);
} catch (ObjectNotFoundException | CommunicationException | SchemaException | ConfigurationException | ExpressionEvaluationException | RuntimeException | Error e) {
ProvisioningUtil.recordFatalError(LOGGER, result, null, e);
result.summarize(true);
throw e;
}
result.addReturn("listeningActivityHandle", listeningActivityHandle);
result.recordSuccess();
result.cleanupResult();
return listeningActivityHandle;
}
@Override
public void stopListeningForAsyncUpdates(@NotNull String listeningActivityHandle, Task task, OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName() + ".stopListeningForAsyncUpdates");
result.addParam("listeningActivityHandle", listeningActivityHandle);
try {
LOGGER.trace("Stopping listening for async updates for {}", listeningActivityHandle);
shadowCache.stopListeningForAsyncUpdates(listeningActivityHandle, task, result);
} catch (RuntimeException | Error e) {
ProvisioningUtil.recordFatalError(LOGGER, result, null, e);
result.summarize(true);
throw e;
}
result.recordSuccess();
result.cleanupResult();
}
@Override
public AsyncUpdateListeningActivityInformationType getAsyncUpdatesListeningActivityInformation(@NotNull String listeningActivityHandle, Task task, OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName() + ".getAsyncUpdatesListeningActivityInformation");
result.addParam("listeningActivityHandle", listeningActivityHandle);
try {
AsyncUpdateListeningActivityInformationType rv = shadowCache.getAsyncUpdatesListeningActivityInformation(listeningActivityHandle, task, result);
result.recordSuccess();
result.cleanupResult();
return rv;
} catch (RuntimeException | Error e) {
ProvisioningUtil.recordFatalError(LOGGER, result, null, e);
result.summarize(true);
throw e;
}
}
private PrismProperty<?> getTokenProperty(ResourceShadowDiscriminator shadowCoordinates, Task task, OperationResult result)
throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, ExpressionEvaluationException {
PrismProperty<?> taskTokenProperty = task.getExtensionPropertyOrClone(SchemaConstants.SYNC_TOKEN);
if (taskTokenProperty != null) {
if (taskTokenProperty.getAnyRealValue() != null) {
return taskTokenProperty;
} else {
LOGGER.warn("Sync token exists, but it is empty (null value). Ignoring it.");
LOGGER.trace("Empty sync token property:\n{}", taskTokenProperty.debugDumpLazily());
}
}
// if the token is not specified in the task, get the latest token
PrismProperty<?> resourceTokenProperty = shadowCache.fetchCurrentToken(shadowCoordinates, result);
if (resourceTokenProperty != null && resourceTokenProperty.getValue() != null &&
resourceTokenProperty.getValue().getValue() != null) {
return resourceTokenProperty;
} else {
LOGGER.warn("Empty current sync token provided by {}", shadowCoordinates);
return null;
}
}
@NotNull
@Override
public <T extends ObjectType> SearchResultList<PrismObject<T>> searchObjects(Class<T> type, ObjectQuery query,
Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult parentResult)
throws SchemaException, ObjectNotFoundException, CommunicationException,
ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName() + ".searchObjects");
result.addParam("objectType", type);
result.addParam("query", query);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Start of (non-iterative) search objects. Query:\n{}", query != null ? query.debugDump(1) : " (null)");
}
query = simplifyQueryFilter(query);
ObjectFilter filter = query != null ? query.getFilter() : null;
if (InternalsConfig.consistencyChecks && filter != null) {
// We may not have all the definitions here. We will apply the definitions later
filter.checkConsistence(false);
}
if (filter instanceof NoneFilter) {
result.recordSuccessIfUnknown();
result.cleanupResult();
SearchResultMetadata metadata = new SearchResultMetadata();
metadata.setApproxNumberOfAllResults(0);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Finished searching. Nothing to do. Filter is NONE. Metadata: {}", metadata.shortDump());
}
SearchResultList<PrismObject<T>> objListType = new SearchResultList<>(new ArrayList<>());
objListType.setMetadata(metadata);
return objListType;
}
SearchResultList<PrismObject<T>> objects;
if (ShadowType.class.isAssignableFrom(type)) {
try {
//noinspection unchecked
objects = (SearchResultList) shadowCache.searchObjects(query, options, task, result);
} catch (Throwable e) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Could not search objects: " + e.getMessage(), e);
throw e;
}
} else {
objects = searchRepoObjects(type, query, options, task, result);
}
result.computeStatus();
result.cleanupResult();
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Finished searching. Metadata: {}", DebugUtil.shortDump(objects.getMetadata()));
}
// validateObjects(objListType);
return objects;
}
@NotNull
@SuppressWarnings("unchecked")
private <T extends ObjectType> SearchResultList<PrismObject<T>> searchRepoObjects(Class<T> type, ObjectQuery query,
Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult result) throws SchemaException {
List<PrismObject<T>> repoObjects;
// TODO: should searching connectors trigger rediscovery?
Collection<SelectorOptions<GetOperationOptions>> repoOptions = null;
if (GetOperationOptions.isReadOnly(SelectorOptions.findRootOptions(options))) {
repoOptions = SelectorOptions.createCollection(GetOperationOptions.createReadOnly());
}
repoObjects = getCacheRepositoryService().searchObjects(type, query, repoOptions, result);
SearchResultList<PrismObject<T>> newObjListType = new SearchResultList(new ArrayList<PrismObject<T>>());
for (PrismObject<T> repoObject : repoObjects) {
OperationResult objResult = new OperationResult(ProvisioningService.class.getName()
+ ".searchObjects.object");
try {
PrismObject<T> completeResource = completeObject(type, repoObject, options, task, objResult);
objResult.computeStatusIfUnknown();
if (!objResult.isSuccess()) {
completeResource.asObjectable().setFetchResult(objResult.createOperationResultType()); // necessary e.g. to skip validation for resources that had issues when checked
result.addSubresult(objResult);
}
newObjListType.add(completeResource);
// TODO: what else do to with objResult??
} catch (ObjectNotFoundException | SchemaException | CommunicationException | ConfigurationException | ExpressionEvaluationException e) {
LOGGER.error("Error while completing {}: {}-{}. Using non-complete object.", repoObject, e.getMessage(), e);
objResult.recordFatalError(e);
repoObject.asObjectable().setFetchResult(objResult.createOperationResultType());
newObjListType.add(repoObject);
result.addSubresult(objResult);
result.recordPartialError(e);
} catch (RuntimeException e) {
// FIXME: Strictly speaking, the runtime exception should
// not be handled here.
// The runtime exceptions should be considered fatal anyway
// ... but some of the
// ICF exceptions are still translated to system exceptions.
// So this provides
// a better robustness now.
LOGGER.error("System error while completing {}: {}-{}. Using non-complete object.", repoObject, e.getMessage(), e);
objResult.recordFatalError(e);
repoObject.asObjectable().setFetchResult(objResult.createOperationResultType());
newObjListType.add(repoObject);
result.addSubresult(objResult);
result.recordPartialError(e);
}
}
return newObjListType;
}
// TODO: move to ResourceManager and ConnectorManager
// the shadow-related code is already in the ShadowCache
private <T extends ObjectType> PrismObject<T> completeObject(Class<T> type, PrismObject<T> inObject,
Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
if (ResourceType.class.equals(type)) {
PrismObject<ResourceType> completeResource = resourceManager.getResource((PrismObject<ResourceType>) inObject,
SelectorOptions.findRootOptions(options), task, result);
return (PrismObject<T>) completeResource;
} else if (ShadowType.class.equals(type)) {
// should not happen, the shadow-related code is already in the ShadowCache
throw new IllegalStateException("BOOOM!");
} else {
//TODO: connectors etc..
}
return inObject;
}
public <T extends ObjectType> Integer countObjects(Class<T> type, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult parentResult)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
OperationResult result = parentResult.createMinorSubresult(ProvisioningService.class.getName() + ".countObjects");
result.addParam("objectType", type);
result.addParam("query", query);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
query = simplifyQueryFilter(query);
ObjectFilter filter = query != null ? query.getFilter() : null;
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Start of counting objects. Query:\n{}", query != null ? query.debugDump(1) : " (null)");
}
if (filter != null && filter instanceof NoneFilter) {
result.recordSuccessIfUnknown();
result.cleanupResult();
LOGGER.trace("Finished counting. Nothing to do. Filter is NONE");
return 0;
}
GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options);
if (!ShadowType.class.isAssignableFrom(type) || GetOperationOptions.isNoFetch(rootOptions) || GetOperationOptions.isRaw(rootOptions)) {
int count = getCacheRepositoryService().countObjects(type, query, options, parentResult);
result.computeStatus();
result.recordSuccessIfUnknown();
result.cleanupResult();
return count;
}
Integer count;
try {
count = shadowCache.countObjects(query, task, result);
result.computeStatus();
} catch (ConfigurationException | CommunicationException | ObjectNotFoundException | SchemaException | ExpressionEvaluationException | RuntimeException | Error e) {
ProvisioningUtil.recordFatalError(LOGGER, result, null, e);
throw e;
} finally {
result.cleanupResult();
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Finished counting objects: {}", count);
}
return count;
}
@SuppressWarnings("rawtypes")
@Override
public <T extends ObjectType> String modifyObject(Class<T> type, String oid,
Collection<? extends ItemDelta> modifications, OperationProvisioningScriptsType scripts, ProvisioningOperationOptions options, Task task, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException,
SecurityViolationException, PolicyViolationException, ObjectAlreadyExistsException, ExpressionEvaluationException {
Validate.notNull(oid, "OID must not be null.");
Validate.notNull(modifications, "Modifications must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
if (InternalsConfig.encryptionChecks) {
CryptoUtil.checkEncrypted(modifications);
}
if (InternalsConfig.consistencyChecks) {
ItemDeltaCollectionsUtil.checkConsistence(modifications);
}
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName() + ".modifyObject");
result.addArbitraryObjectCollectionAsParam("modifications", modifications);
result.addParam(OperationResult.PARAM_OID, oid);
result.addArbitraryObjectAsParam("scripts", scripts);
result.addArbitraryObjectAsParam("options", options);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("modifyObject: object modifications:\n{}", DebugUtil.debugDump(modifications));
}
// getting object to modify
PrismObject<T> repoShadow = getRepoObject(type, oid, null, result);
LOGGER.trace("modifyObject: object to modify (repository):\n{}.", repoShadow.debugDumpLazily());
try {
if (ShadowType.class.isAssignableFrom(type)) {
// calling shadow cache to modify object
//noinspection unchecked
oid = shadowCache.modifyShadow((PrismObject<ShadowType>)repoShadow, modifications, scripts, options, task,
result);
} else {
cacheRepositoryService.modifyObject(type, oid, modifications, result);
}
if (!result.isInProgress()) {
// This is the case when there is already a conflicting pending operation.
result.computeStatus();
}
} catch (CommunicationException | SchemaException | ObjectNotFoundException | ConfigurationException | SecurityViolationException
| PolicyViolationException | ExpressionEvaluationException | RuntimeException | Error e) {
ProvisioningUtil.recordFatalError(LOGGER, result, null, e);
throw e;
} catch (GenericFrameworkException e) {
ProvisioningUtil.recordFatalError(LOGGER, result, null, e);
throw new CommunicationException(e.getMessage(), e);
} catch (EncryptionException e) {
ProvisioningUtil.recordFatalError(LOGGER, result, null, e);
throw new SystemException(e.getMessage(), e);
} catch (ObjectAlreadyExistsException e) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't modify object: object after modification would conflict with another existing object: " + e.getMessage(), e);
throw e;
}
result.cleanupResult();
return oid;
}
@Override
public <T extends ObjectType> PrismObject<T> deleteObject(Class<T> type, String oid, ProvisioningOperationOptions options, OperationProvisioningScriptsType scripts,
Task task, OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, SchemaException,
ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException {
Validate.notNull(oid, "Oid of object to delete must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
LOGGER.trace("Start to delete object with oid {}", oid);
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName() + ".deleteObject");
result.addParam("oid", oid);
result.addArbitraryObjectAsParam("scripts", scripts);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
//TODO: is critical when shadow does not exits anymore?? do we need to log it?? if not, change null to allowNotFound options
PrismObject<T> object = getRepoObject(type, oid, null, result);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Object from repository to delete:\n{}", object.debugDump(1));
}
PrismObject<T> deadShadow = null;
if (object.canRepresent(ShadowType.class) && !ProvisioningOperationOptions.isRaw(options)) {
try {
deadShadow = (PrismObject<T>) shadowCache.deleteShadow((PrismObject<ShadowType>)object, options, scripts, task, result);
} catch (CommunicationException e) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: communication problem: " + e.getMessage(), e);
throw new CommunicationException(e.getMessage(), e);
} catch (GenericFrameworkException e) {
ProvisioningUtil.recordFatalError(LOGGER, result,
"Couldn't delete object: generic error in the connector: " + e.getMessage(), e);
throw new CommunicationException(e.getMessage(), e);
} catch (SchemaException e) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: schema problem: " + e.getMessage(), e);
throw new SchemaException(e.getMessage(), e);
} catch (ConfigurationException e) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: configuration problem: " + e.getMessage(), e);
throw e;
} catch (SecurityViolationException e) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: security violation: " + e.getMessage(), e);
throw e;
} catch (ExpressionEvaluationException e) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: expression errror: " + e.getMessage(), e);
throw e;
} catch (PolicyViolationException | RuntimeException | Error e) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: " + e.getMessage(), e);
throw e;
}
} else if (object.canRepresent(ResourceType.class)) {
resourceManager.deleteResource(oid, options, task, result);
} else {
try {
getCacheRepositoryService().deleteObject(type, oid, result);
} catch (ObjectNotFoundException ex) {
result.recordFatalError(ex);
result.cleanupResult(ex);
throw ex;
}
}
LOGGER.trace("Finished deleting object.");
if (!result.isInProgress()) {
// This is the case when there is already a conflicting pending operation.
result.computeStatus();
}
result.cleanupResult();
return deadShadow;
}
/* (non-Javadoc)
* @see com.evolveum.midpoint.provisioning.api.ProvisioningService#executeScript(java.lang.Class, java.lang.String, com.evolveum.midpoint.xml.ns._public.common.common_3.ProvisioningScriptType, com.evolveum.midpoint.task.api.Task, com.evolveum.midpoint.schema.result.OperationResult)
*/
@Override
public <T extends ObjectType> Object executeScript(String resourceOid, ProvisioningScriptType script,
Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException,
CommunicationException, ConfigurationException, SecurityViolationException, ObjectAlreadyExistsException, ExpressionEvaluationException {
Validate.notNull(resourceOid, "Oid of object for script execution must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName() + ".executeScript");
result.addParam("oid", resourceOid);
result.addArbitraryObjectAsParam("script", script);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
Object scriptResult;
try {
scriptResult = resourceManager.executeScript(resourceOid, script, task, result);
} catch (CommunicationException | SchemaException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException | RuntimeException | Error e) {
ProvisioningUtil.recordFatalError(LOGGER, result, null, e);
throw e;
}
result.computeStatus();
result.cleanupResult();
return scriptResult;
}
@Override
public OperationResult testResource(String resourceOid, Task task) throws ObjectNotFoundException {
// We are not going to create parent result here. We don't want to
// pollute the result with
// implementation details, as this will be usually displayed in the
// table of "test resource" results.
Validate.notNull(resourceOid, "Resource OID to test is null.");
LOGGER.trace("Start testing resource with oid {} ", resourceOid);
OperationResult testResult = new OperationResult(ConnectorTestOperation.TEST_CONNECTION.getOperation());
testResult.addParam("resourceOid", resourceOid);
testResult.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
PrismObject<ResourceType> resource;
try {
resource = getRepoObject(ResourceType.class, resourceOid, null, testResult);
resourceManager.testConnection(resource, task, testResult);
} catch (SchemaException ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
testResult.computeStatus("Test resource has failed");
LOGGER.debug("Finished testing {}, result: {} ", resource,
testResult.getStatus());
return testResult;
}
@Deprecated
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public List<PrismObject<? extends ShadowType>> listResourceObjects(String resourceOid,
QName objectClass, ObjectPaging paging, Task task, OperationResult parentResult) throws SchemaException,
ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
final OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName()
+ ".listResourceObjects");
result.addParam("resourceOid", resourceOid);
result.addParam("objectClass", objectClass);
result.addArbitraryObjectAsParam("paging", paging);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
if (resourceOid == null) {
throw new IllegalArgumentException("Resource not defined in a search query");
}
if (objectClass == null) {
throw new IllegalArgumentException("Objectclass not defined in a search query");
}
ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resourceOid, objectClass, prismContext);
final List<PrismObject<? extends ShadowType>> objectList = new ArrayList<>();
final ResultHandler<ShadowType> shadowHandler = new ResultHandler<ShadowType>() {
@Override
public boolean handle(PrismObject<ShadowType> shadow, OperationResult objResult) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("listResourceObjects: processing shadow: {}", SchemaDebugUtil.prettyPrint(shadow));
}
objectList.add(shadow);
return true;
}
};
try {
shadowCache.searchObjectsIterative(query, null, shadowHandler, false, task, result);
} catch (SchemaException | ObjectNotFoundException | CommunicationException |
ConfigurationException | SecurityViolationException | ExpressionEvaluationException | RuntimeException | Error ex) {
result.recordFatalError(ex.getMessage(), ex);
result.cleanupResult(ex);
throw ex;
}
result.cleanupResult();
return objectList;
}
@Override
public void refreshShadow(PrismObject<ShadowType> shadow, ProvisioningOperationOptions options, Task task, OperationResult parentResult)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
ObjectAlreadyExistsException, SecurityViolationException, ExpressionEvaluationException {
Validate.notNull(shadow, "Shadow for refresh must not be null.");
OperationResult result = parentResult.createSubresult(OPERATION_REFRESH_SHADOW);
LOGGER.debug("Refreshing shadow {}", shadow);
try {
shadowCache.refreshShadow(shadow, task, result);
} catch (CommunicationException | SchemaException | ObjectNotFoundException | ConfigurationException | ExpressionEvaluationException | RuntimeException | Error e) {
ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't refresh shadow: " + e.getClass().getSimpleName() + ": "+ e.getMessage(), e);
throw e;
} catch (EncryptionException e) {
ProvisioningUtil.recordFatalError(LOGGER, result, null, e);
throw new SystemException(e.getMessage(), e);
}
result.computeStatus();
result.cleanupResult();
LOGGER.debug("Finished refreshing shadow {}: {}", shadow, result);
}
// TODO: move to ResourceManager and ConnectorManager
// the shadow-related code is already in the ShadowCache
private <T extends ObjectType> boolean handleRepoObject(final Class<T> type, PrismObject<T> object,
final Collection<SelectorOptions<GetOperationOptions>> options,
final ResultHandler<T> handler, Task task, final OperationResult objResult) {
PrismObject<T> completeObject;
try {
completeObject = completeObject(type, object, options, task, objResult);
} catch (Throwable e) {
LOGGER.error("Error while completing {}: {}-{}. Using non-complete object.", object, e.getMessage(), e);
objResult.recordFatalError(e);
object.asObjectable().setFetchResult(objResult.createOperationResultType());
completeObject = object;
}
objResult.computeStatus();
objResult.recordSuccessIfUnknown();
if (!objResult.isSuccess()) {
OperationResultType resultType = objResult.createOperationResultType();
completeObject.asObjectable().setFetchResult(resultType);
}
return handler.handle(completeObject, objResult);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public <T extends ObjectType> SearchResultMetadata searchObjectsIterative(final Class<T> type, ObjectQuery query,
final Collection<SelectorOptions<GetOperationOptions>> options,
final ResultHandler<T> handler, Task task, final OperationResult parentResult) throws SchemaException,
ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
Validate.notNull(parentResult, "Operation result must not be null.");
Validate.notNull(handler, "Handler must not be null.");
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Start of (iterative) search objects. Query:\n{}", query != null ? query.debugDump(1) : " (null)");
}