-
Notifications
You must be signed in to change notification settings - Fork 460
/
AbstractOperationContext.java
1800 lines (1598 loc) · 77.1 KB
/
AbstractOperationContext.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 The WildFly Authors
* SPDX-License-Identifier: Apache-2.0
*/
package org.jboss.as.controller;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTE_VALUE_WRITTEN_NOTIFICATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CANCELLED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.LEVEL;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_REQUIRES_RELOAD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_REQUIRES_RESTART;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESOURCE_ADDED_NOTIFICATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESOURCE_REMOVED_NOTIFICATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESPONSE_HEADERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLBACK_ON_RUNTIME_FAILURE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLED_BACK;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLOUT_PLAN;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RUNTIME_UPDATE_SKIPPED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUPS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WARNING;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WARNINGS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.logging.ControllerLogger.MGMT_OP_LOGGER;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import java.util.logging.Level;
import org.jboss.as.controller.ConfigurationChangesCollector.ConfigurationChange;
import org.jboss.as.controller.access.Environment;
import org.jboss.as.controller.audit.AuditLogger;
import org.jboss.as.controller.capability.registry.RuntimeCapabilityRegistry;
import org.jboss.as.controller.client.MessageSeverity;
import org.jboss.as.controller.client.OperationResponse;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.notification.Notification;
import org.jboss.as.controller.notification.NotificationSupport;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.operations.global.ReadResourceHandler;
import org.jboss.as.controller.persistence.ConfigurationPersistenceException;
import org.jboss.as.controller.persistence.ConfigurationPersister;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ImmutableManagementResourceRegistration;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.NotificationEntry;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.core.security.AccessMechanism;
import org.jboss.as.protocol.StreamUtils;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.common.Assert;
import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Base class for operation context implementations.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
@SuppressWarnings("deprecation")
abstract class AbstractOperationContext implements OperationContext, AutoCloseable {
private static final Set<String> NON_COPIED_HEADERS =
Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(ALLOW_RESOURCE_SERVICE_RESTART,
ROLLBACK_ON_RUNTIME_FAILURE, ROLLOUT_PLAN)));
private static final Set<ControlledProcessState.State> RUNTIME_LIMITED_STATES =
EnumSet.of(ControlledProcessState.State.RELOAD_REQUIRED, ControlledProcessState.State.RESTART_REQUIRED);
static final ThreadLocal<Thread> controllingThread = new ThreadLocal<Thread>();
/** Thread that initiated execution of the overall operation for which this context is the whole or a part */
final Thread initiatingThread;
private final EnumMap<Stage, Deque<Step>> steps;
private final ModelController.OperationTransactionControl transactionControl;
final ControlledProcessState processState;
final NotificationSupport notificationSupport;
final OperationHeaders operationHeaders;
private final boolean booting;
private final ProcessType processType;
private final RunningMode runningMode;
private final Environment callEnvironment;
private final ConfigurationChangesCollector configurationChangesCollector = ConfigurationChangesCollector.INSTANCE;
// We only respect interruption on the way in; once we complete all steps
// and begin
// returning, any calls that can throw InterruptedException are converted to
// an uninterruptible form. This is to ensure rollback changes are not
// interrupted
volatile boolean respectInterruption = true;
/**
* The notifications are stored when {@code emit(Notification)} is called and effectively
* emitted at the end of the operation execution if it is successful
*/
private final Queue<Notification> notifications;
/**
* Notifications descriptions are checked in {@code emit(Notification)} to use the resource registration
* when the operation is performed on the resource [WFCORE-1007]
* Similar to {@code notifications}, the eventual warnings will be buffered and actually logged
* at the end of the operation execution if it is successful.
*/
private final Queue<String> missingNotificationDescriptionWarnings;
Stage currentStage = Stage.MODEL;
ResultAction resultAction;
/** Tracks whether we've detected cancellation */
boolean cancelled;
/** Currently executing step */
Step activeStep;
/** The step that acquired the write lock */
Step lockStep;
private final Supplier<SecurityIdentity> securityIdentitySupplier;
/** Whether operation execution has begun; i.e. whether completeStep() has been called */
private boolean executing;
/** First response node provided to addStep */
ModelNode initialResponse;
/** Operation provided to addStep along with initialResponse */
ModelNode initialOperation;
/** Operations that were added by the controller, before execution started */
private final List<ModelNode> controllerOperations = new ArrayList<ModelNode>(2);
private boolean auditLogged;
private final AuditLogger auditLogger;
private final ModelControllerImpl controller;
private final OperationStepHandler extraValidationStepHandler;
// protected by this
private Map<String, OperationResponse.StreamEntry> responseStreams;
private final Level WARNING_DEFAULT_LEVEL = Level.WARNING;
/**
* Resources modified by this context's operations. May be modified by ParallelBootOperationStepHandler which spawns threads,
* so guard by itself.
* If validation is to be skipped this will be {@code null}
*/
private final Set<PathAddress> modifiedResourcesForModelValidation;
enum ContextFlag {
ROLLBACK_ON_FAIL, ALLOW_RESOURCE_SERVICE_RESTART,
}
AbstractOperationContext(final ProcessType processType,
final RunningMode runningMode,
final ModelController.OperationTransactionControl transactionControl,
final ControlledProcessState processState,
final boolean booting,
final AuditLogger auditLogger,
final NotificationSupport notificationSupport,
final ModelControllerImpl controller,
final boolean skipModelValidation,
final OperationStepHandler extraValidationStepHandler,
final OperationHeaders operationHeaders,
final Supplier<SecurityIdentity> securityIdentitySupplier) {
this.processType = processType;
this.runningMode = runningMode;
this.transactionControl = transactionControl;
this.processState = processState;
this.booting = booting;
this.auditLogger = auditLogger;
this.notificationSupport = notificationSupport;
this.notifications = new ConcurrentLinkedQueue<Notification>();
this.missingNotificationDescriptionWarnings = new ConcurrentLinkedQueue<String>();
this.controller = controller;
steps = new EnumMap<Stage, Deque<Step>>(Stage.class);
for (Stage stage : Stage.values()) {
if (booting && stage == Stage.VERIFY) {
// Use a concurrent structure as the parallel boot threads will
// concurrently add steps
steps.put(stage, new LinkedBlockingDeque<Step>());
} else {
steps.put(stage, new ArrayDeque<Step>());
}
}
initiatingThread = Thread.currentThread();
this.callEnvironment = new Environment(processState, processType);
modifiedResourcesForModelValidation = skipModelValidation == false ? new HashSet<PathAddress>() : null;
this.extraValidationStepHandler = extraValidationStepHandler;
this.operationHeaders = operationHeaders == null ? OperationHeaders.forInternalCall() : operationHeaders;
this.securityIdentitySupplier = securityIdentitySupplier;
}
/**
* Internal access to the management model implementation.
*
* @return the management model
*/
abstract ModelControllerImpl.ManagementModelImpl getManagementModel();
/**
* Internal helper to read a resource from a given management model.
*
* @param model the management model to read from
* @param address the absolute path address
* @param recursive whether to read the model recursive or not
* @return the resource
*/
abstract Resource readResourceFromRoot(final ManagementModel model, final PathAddress address, final boolean recursive);
@Override
public boolean isBooting() {
return booting;
}
@Override
public void addStep(final OperationStepHandler step, final Stage stage) throws IllegalArgumentException {
addStep(step, stage, false);
}
@Override
public void addStep(final ModelNode operation, final OperationStepHandler step, final Stage stage)
throws IllegalArgumentException {
final ModelNode response = activeStep == null ? new ModelNode().setEmptyObject() : activeStep.response;
addStep(response, operation, null, step, stage);
}
@Override
public void addStep(final ModelNode operation, final OperationStepHandler step, final Stage stage, final boolean addFirst)
throws IllegalArgumentException {
final ModelNode response = activeStep == null ? new ModelNode().setEmptyObject() : activeStep.response;
addStep(response, operation, null, null, step, stage, addFirst);
}
@Override
public void addStep(final ModelNode response, final ModelNode operation, final OperationStepHandler step, final Stage stage)
throws IllegalArgumentException {
addStep(response, operation, null, step, stage);
}
@Override
public void addStep(OperationStepHandler step, Stage stage, boolean addFirst) throws IllegalArgumentException {
addStep(activeStep.response, activeStep.operation, activeStep.address, null, step, stage, addFirst);
}
@Override
public void addModelStep(OperationDefinition stepDefinition, OperationStepHandler stepHandler, boolean addFirst) throws IllegalArgumentException {
addStep(activeStep.response, activeStep.operation, activeStep.address, stepDefinition, stepHandler, Stage.MODEL, addFirst);
}
@Override
public void addModelStep(ModelNode response, ModelNode operation, OperationDefinition stepDefinition, OperationStepHandler stepHandler, boolean addFirst) throws IllegalArgumentException {
addStep(response, operation, null, stepDefinition, stepHandler, Stage.MODEL, addFirst);
}
void addStep(final ModelNode response, final ModelNode operation, final PathAddress address, final OperationStepHandler step,
final Stage stage) throws IllegalArgumentException {
addStep(response, operation, address, null, step, stage, false);
}
@Override
public void addStep(ModelNode response, ModelNode operation, OperationStepHandler step, Stage stage, boolean addFirst)
throws IllegalArgumentException {
addStep(response, operation, null, null, step, stage, addFirst);
}
void addStep(final ModelNode response, final ModelNode operation, final PathAddress address, OperationDefinition stepDefinition, final OperationStepHandler step,
final Stage stage, boolean addFirst) throws IllegalArgumentException {
assert isControllingThread();
Assert.checkNotNullParam("response", response);
Assert.checkNotNullParam("operation", operation);
Assert.checkNotNullParam("step", step);
Assert.checkNotNullParam("stage", stage);
if (currentStage == Stage.DONE) {
throw ControllerLogger.ROOT_LOGGER.operationAlreadyComplete();
}
if (stage.compareTo(currentStage) < 0) {
throw ControllerLogger.ROOT_LOGGER.stageAlreadyComplete(stage);
}
if (stage == Stage.DOMAIN && !processType.isHostController()) {
throw ControllerLogger.ROOT_LOGGER.invalidStage(stage, processType);
}
if (stage == Stage.DONE) {
throw ControllerLogger.ROOT_LOGGER.invalidStepStage();
}
final PathAddress stepAddress = address != null ? address : PathAddress.pathAddress(operation.get(OP_ADDR));
// Ignore runtime ops against profile resources on an HC
if (stage == Stage.RUNTIME && !processType.isServer() && stepAddress.size() > 1 && PROFILE.equals(stepAddress.getElement(0).getKey())) {
// Log this as it means we have an incorrect OSH
ControllerLogger.ROOT_LOGGER.invalidRuntimeStageForProfile(operation.get(OP).asString(), stepAddress.toCLIStyleString(), stage, processType);
return;
}
if (!booting && activeStep != null) {
// Added steps inherit the caller type of their parent
if (activeStep.operation.hasDefined(OPERATION_HEADERS)) {
ModelNode activeHeaders = activeStep.operation.get(OPERATION_HEADERS);
for (Property property : activeHeaders.asPropertyList()) {
String key = property.getName();
if (!NON_COPIED_HEADERS.contains(key)) {
operation.get(OPERATION_HEADERS, key).set(property.getValue());
}
}
}
}
final Deque<Step> deque = steps.get(stage);
if (addFirst) {
deque.addFirst(new Step(stepDefinition, step, response, operation, stepAddress));
} else {
deque.addLast(new Step(stepDefinition, step, response, operation, stepAddress));
}
if (!executing && stage == Stage.MODEL) {
recordControllerOperation(operation);
if (initialResponse == null) {
initialResponse = response;
initialOperation = operation;
}
}
}
void addBootStep(ParsedBootOp parsedBootOp) {
addStep(parsedBootOp.response, parsedBootOp.operation, parsedBootOp.handler, Stage.MODEL);
// If the op is controlling other ops (i.e. for parallel boot) then record those for audit logging
for (ModelNode childOp : parsedBootOp.getChildOperations()) {
recordControllerOperation(childOp);
}
}
@Override
public void addResponseWarning(final Level level, final String warning) {
final ModelNode modelNodeWarning = new ModelNode(warning);
this.addResponseWarning(level, modelNodeWarning);
}
@Override
public void addResponseWarning(final Level level,final ModelNode warning) {
if(!isWarningLoggable(level)){
return;
}
createWarning(level, warning);
}
private void createWarning(final Level level, final String warning){
final ModelNode modelNodeWarning = new ModelNode(warning);
createWarning(level,modelNodeWarning);
}
private void createWarning(final Level level, final ModelNode warning){
final ModelNode warningEntry = new ModelNode();
warningEntry.get(WARNING).set(warning);
warningEntry.get(LEVEL).set(level.toString());
final ModelNode operation = activeStep.operation;
if(operation != null){
final ModelNode operationEntry = warningEntry.get(OP);
operationEntry.get(OP_ADDR).set(operation.get(OP_ADDR));
operationEntry.get(OP).set(operation.get(OP));
}
final ModelNode warnings = getResponseHeaders().get(WARNINGS);
boolean unique = true;
if (warnings.isDefined()) {
// Don't repeat a warning. This is basically a secondard safeguard
// against different steps for the same op ending up reporting the
// same warning. List iteration is not efficient but > 1 warning
// in an op is an edge case
for (ModelNode existing : warnings.asList()) {
if (existing.equals(warningEntry)) {
unique = false;
break;
}
}
}
if (unique) {
warnings.add(warningEntry);
}
}
private boolean isWarningLoggable(final Level level){
Level thresholdLevel;
String headerLevel = operationHeaders.getWarningLevel();
if (headerLevel != null) {
try {
thresholdLevel = Level.parse(headerLevel);
} catch(Exception e) {
createWarning(Level.ALL, ControllerLogger.ROOT_LOGGER.couldntConvertWarningLevel(headerLevel));
thresholdLevel = Level.ALL;
}
} else {
thresholdLevel = WARNING_DEFAULT_LEVEL;
}
return thresholdLevel.intValue() <= level.intValue();
}
@Override
public final ModelNode getFailureDescription() {
return activeStep.response.get(FAILURE_DESCRIPTION);
}
@Override
public final boolean hasFailureDescription() {
return activeStep.response.has(FAILURE_DESCRIPTION);
}
@Override
public final ModelNode getResponseHeaders() {
return activeStep.response.get(RESPONSE_HEADERS);
}
@Override
public void close() {
this.activeStep = null;
if (modifiedResourcesForModelValidation != null) {
modifiedResourcesForModelValidation.clear();
}
}
/**
* Package-protected method used to initiate operation execution.
* @return the result action
*/
ResultAction executeOperation() {
assert isControllingThread();
try {
/** Execution has begun */
executing = true;
processStages();
if (resultAction == ResultAction.KEEP) {
report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationSucceeded());
} else {
report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationRollingBack());
}
} catch (RuntimeException e) {
handleUncaughtException(e);
ControllerLogger.MGMT_OP_LOGGER.unexpectedOperationExecutionException(e, controllerOperations);
} finally {
// On failure close any attached response streams
if (resultAction != ResultAction.KEEP && !isBooting()) {
synchronized (this) {
if (responseStreams != null) {
int i = 0;
for (OperationResponse.StreamEntry is : responseStreams.values()) {
try {
is.getStream().close();
} catch (Exception e) {
ControllerLogger.MGMT_OP_LOGGER.debugf(e, "Failed closing stream at index %d", i);
}
i++;
}
responseStreams.clear();
}
}
}
}
return resultAction;
}
/** Opportunity to do required cleanup after an exception propagated all the way to {@link #executeOperation()}.*/
void handleUncaughtException(RuntimeException e) {
}
@Override
public final void completeStep(RollbackHandler rollbackHandler) {
Assert.checkNotNullParam("rollbackHandler", rollbackHandler);
if (rollbackHandler == RollbackHandler.NOOP_ROLLBACK_HANDLER) {
completeStep(ResultHandler.NOOP_RESULT_HANDLER);
} else {
completeStep(new RollbackDelegatingResultHandler(rollbackHandler));
}
// we return and executeStep picks it up
}
@Override
public final void completeStep(ResultHandler resultHandler) {
Assert.checkNotNullParam("resultHandler", resultHandler);
this.activeStep.setResultHandler(resultHandler);
// we return and executeStep picks it up
}
@Override
public final PathAddress getCurrentAddress() {
assert activeStep != null;
return activeStep.address;
}
@Override
public final String getCurrentAddressValue() {
PathAddress pa = getCurrentAddress();
if (pa.size() == 0) {
throw new IllegalStateException();
}
return pa.getLastElement().getValue();
}
@Override
public final String getCurrentOperationName() {
assert activeStep != null;
ModelNode operation = activeStep.operation;
assert operation != null;
return operation.get(OP).asString();
}
@Override
public final ModelNode getCurrentOperationParameter(final String parameterName) {
return getCurrentOperationParameter(parameterName, true);
}
@Override
public final ModelNode getCurrentOperationParameter(final String parameterName, boolean nullable) {
if (isLegalParameterName(parameterName)) {
assert activeStep != null;
ModelNode operation = activeStep.operation;
assert operation != null;
if (!operation.has(parameterName) && nullable) {
return null;
} else {
return operation.get(parameterName);
}
} else {
throw ControllerLogger.ROOT_LOGGER.invalidParameterName(parameterName);
}
}
private boolean isLegalParameterName(final String parameterName) {
return !(parameterName.equals(OP) || parameterName.equals(OP_ADDR) || parameterName.equals(OPERATION_HEADERS));
}
/**
* Notification that all steps in a stage have been executed.
* <p>This default implementation always returns {@code true}.</p>
* @param stage the stage that is completed. Will not be {@code null}
*
* @return {@code true} if execution should proceed to the next stage; {@code false} if execution should halt
*/
boolean stageCompleted(Stage stage) {
return true;
}
/**
* If appropriate for this implementation, block waiting for the
* {@link ModelControllerImpl#awaitContainerStability(long, java.util.concurrent.TimeUnit, boolean)} method to return,
* ensuring that the controller's MSC ServiceContainer is settled and it is safe to proceed to service status verification.
*
* @throws InterruptedException if the thread is interrupted while blocking
* @throws java.util.concurrent.TimeoutException if attaining container stability takes an unacceptable amount of time
*/
abstract void awaitServiceContainerStability() throws InterruptedException, TimeoutException;
/**
* Create a persistence resource (if appropriate for this implementation) for use in persisting the configuration
* model that results from this operation. If a resource is created, it should perform as much persistence work
* as possible without modifying the official persistence store (i.e. the config file) in order to detect any
* persistence issues.
*
* @return the persistence resource, or {@code null} if persistence is not supported
*
* @throws ConfigurationPersistenceException if there is a problem creating the persistence resource
*/
abstract ConfigurationPersister.PersistenceResource createPersistenceResource() throws ConfigurationPersistenceException;
/**
* Notification that the operation is not going to proceed to normal completion.
*/
abstract void operationRollingBack();
/**
* Release any locks held by the given step.
*
* @param step the step
*/
abstract void releaseStepLocks(AbstractStep step);
/**
* Wait for completion of removal of any services removed by this context.
*
* @throws InterruptedException if the thread is interrupted while waiting
*/
abstract void waitForRemovals() throws InterruptedException, TimeoutException;
/**
* Gets whether any steps have taken actions that indicate a wish to write to the model or the service container.
*
* @return {@code true} if no
*/
abstract boolean isReadOnly();
/**
* Gets a reference to the mutable ManagementResourceRegistration for the resource tree root.
* @return the registration.
*/
abstract ManagementResourceRegistration getRootResourceRegistrationForUpdate();
/**
* Gets whether the currently executing thread is allowed to control this operation context.
*
* @return {@code true} if the currently executing thread is allowed to control the context
*/
boolean isControllingThread() {
return Thread.currentThread() == initiatingThread || controllingThread.get() == initiatingThread;
}
/**
* Log an audit record of this operation.
*/
void logAuditRecord() {
trackConfigurationChange();
if (!auditLogged) {
try {
AccessAuditContext accessContext = SecurityActions.currentAccessAuditContext();
SecurityIdentity identity = getSecurityIdentity();
auditLogger.log(
isReadOnly(),
resultAction,
identity == null ? null : identity.getPrincipal().getName(),
accessContext == null ? null : accessContext.getDomainUuid(),
accessContext == null ? null : accessContext.getAccessMechanism(),
accessContext == null ? null : accessContext.getRemoteAddress(),
getModel(),
controllerOperations);
auditLogged = true;
} catch (Exception e) {
ControllerLogger.MGMT_OP_LOGGER.failedToUpdateAuditLog(e);
}
}
}
/**
* Record an operation added before execution began (i.e. added by the controller and not by a step)
* @param operation the operation
*/
private void recordControllerOperation(ModelNode operation) {
controllerOperations.add(operation.clone()); // clone so we don't log op nodes mutated during execution
}
void recordWriteLock() {
this.lockStep = activeStep.recordWriteLock();
}
void trackConfigurationChange() {
if (!isBooting() && !isReadOnly() && configurationChangesCollector.trackAllowed()) {
try {
AccessAuditContext accessContext = SecurityActions.currentAccessAuditContext();
SecurityIdentity identity = getSecurityIdentity();
configurationChangesCollector.addConfigurationChanges(new ConfigurationChange(resultAction,
identity == null ? null : identity.getPrincipal().getName(),
accessContext == null ? null : accessContext.getDomainUuid(),
accessContext == null ? null : accessContext.getAccessMechanism(),
accessContext == null ? null : accessContext.getRemoteAddress(),
controllerOperations));
} catch (Exception e) {
ControllerLogger.MGMT_OP_LOGGER.failedToUpdateAuditLog(e);
}
}
}
abstract Resource getModel();
/**
* Indicates whether the capabilities associated with the resource addressed by the current step
* require a reload or a restart before any Stage.RUNTIME execution can happen.
* Should only be invoked if the overall process state requires reload/restart
* and the step is not for a runtime-only operation or resource.
*
* @param step the step. Cannot be {@code null}
* @return {@link org.jboss.as.controller.capability.registry.RuntimeCapabilityRegistry.RuntimeStatus} for the resource
* associated with {@code step}
*/
CapabilityRegistry.RuntimeStatus getStepCapabilityStatus(Step step) {
return RuntimeCapabilityRegistry.RuntimeStatus.NORMAL;
}
/**
* Perform the work of processing the various OperationContext.Stage queues, and then the DONE stage.
*/
private void processStages() {
// Locate the next step to execute.
ModelNode primaryResponse = null;
do {
Step step = steps.get(currentStage).pollFirst();
if (step == null) {
if (currentStage == Stage.MODEL && addModelValidationSteps()) {
continue;
}
// No steps remain in this stage; give subclasses a chance to check status
// and approve moving to the next stage
if (!tryStageCompleted(currentStage)) {
// Can't continue
resultAction = ResultAction.ROLLBACK;
executeResultHandlerPhase(null);
return;
}
// Proceed to the next stage
if (currentStage.hasNext()) {
currentStage = currentStage.next();
if (currentStage == Stage.VERIFY) {
// a change was made to the runtime. Thus, we must wait
// for stability before resuming in to verify.
try {
awaitServiceContainerStability();
} catch (InterruptedException e) {
cancelled = true;
handleContainerStabilityFailure(primaryResponse, e);
executeResultHandlerPhase(null);
return;
} catch (TimeoutException te) {
// The service container is in an unknown state; but we don't require restart
// because rollback may allow the container to stabilize. We force require-restart
// in the rollback handling if the container cannot stabilize (see OperationContextImpl.releaseStepLocks)
//processState.setRestartRequired(); // don't use our restartRequired() method as this is not reversible in rollback
handleContainerStabilityFailure(primaryResponse, te);
executeResultHandlerPhase(null);
return;
}
}
}
} else {
// The response to the first step is what goes to the outside caller
if (primaryResponse == null) {
primaryResponse = step.response;
}
// Execute the step, but make sure we always finalize any steps
Throwable toThrow = null;
// Whether to return after try/finally
boolean exit = false;
try {
CapabilityRegistry.RuntimeStatus stepStatus = getStepExecutionStatus(step);
if (stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.NORMAL) {
executeStep(step);
} else {
String header = stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.RESTART_REQUIRED
? OPERATION_REQUIRES_RESTART : OPERATION_REQUIRES_RELOAD;
step.response.get(RESPONSE_HEADERS, header).set(true);
}
} catch (RuntimeException | Error re) {
resultAction = ResultAction.ROLLBACK;
toThrow = re;
} finally {
// See if executeStep put us in a state where we shouldn't do any more
if (toThrow != null || !canContinueProcessing()) {
// We're done.
executeResultHandlerPhase(toThrow);
exit = true; // we're on the return path
}
}
if (exit) {
return;
}
}
} while (currentStage != Stage.DONE);
assert primaryResponse != null; // else ModelControllerImpl executed an op with no steps
// All steps ran and canContinueProcessing returned true for the last one, so...
executeDoneStage(primaryResponse);
}
private CapabilityRegistry.RuntimeStatus getStepExecutionStatus(Step step) {
if (booting || currentStage != Stage.RUNTIME || !RUNTIME_LIMITED_STATES.contains(processState.getState())
|| (step.operationDefinition != null && (step.operationDefinition.getFlags().contains(OperationEntry.Flag.READ_ONLY)
|| step.operationDefinition.getFlags().contains(OperationEntry.Flag.RUNTIME_ONLY)))) {
return RuntimeCapabilityRegistry.RuntimeStatus.NORMAL;
}
ImmutableManagementResourceRegistration mrr = step.getManagementResourceRegistration(getManagementModel());
if (mrr != null) {
if (mrr.isRuntimeOnly()) {
return RuntimeCapabilityRegistry.RuntimeStatus.NORMAL;
}
String opName = step.operationDefinition != null ? step.operationDefinition.getName() : null;
if ((WRITE_ATTRIBUTE_OPERATION.equals(opName) || UNDEFINE_ATTRIBUTE_OPERATION.equals(opName)) && step.operation.hasDefined(NAME)) {
String attrName = step.operation.get(NAME).asString();
AttributeAccess aa = mrr.getAttributeAccess(PathAddress.EMPTY_ADDRESS, attrName);
if (aa != null && aa.getStorageType() == AttributeAccess.Storage.RUNTIME) {
return RuntimeCapabilityRegistry.RuntimeStatus.NORMAL;
}
}
}
return getStepCapabilityStatus(step);
}
private boolean tryStageCompleted(Stage currentStage) {
boolean result;
try {
result = stageCompleted(currentStage);
} catch (RuntimeException e) {
result = false;
if (!initialResponse.hasDefined(FAILURE_DESCRIPTION)) {
initialResponse.get(FAILURE_DESCRIPTION).set(ControllerLogger.MGMT_OP_LOGGER.unexpectedOperationExecutionFailureDescription(e));
}
ControllerLogger.MGMT_OP_LOGGER.unexpectedOperationExecutionException(e, controllerOperations);
}
return result;
}
private void executeDoneStage(ModelNode primaryResponse) {
// All steps are completed without triggering rollback;
// time for final processing
Throwable toThrow = null;
try {
// Prepare persistence of any configuration changes
ConfigurationPersister.PersistenceResource persistenceResource = null;
if (resultAction != ResultAction.ROLLBACK) {
try {
persistenceResource = createPersistenceResource();
} catch (ConfigurationPersistenceException e) {
MGMT_OP_LOGGER.failedToPersistConfigurationChange(e);
primaryResponse.get(OUTCOME).set(FAILED);
primaryResponse.get(FAILURE_DESCRIPTION).set(ControllerLogger.ROOT_LOGGER.failedToPersistConfigurationChange(e.getLocalizedMessage()));
resultAction = ResultAction.ROLLBACK;
executeResultHandlerPhase(null);
return;
}
}
// Allow any containing TransactionControl to vote
final AtomicReference<ResultAction> ref = new AtomicReference<ResultAction>(
transactionControl == null ? ResultAction.KEEP : ResultAction.ROLLBACK);
if (transactionControl != null) {
if (MGMT_OP_LOGGER.isTraceEnabled()) {
MGMT_OP_LOGGER.trace("Prepared response is " + activeStep.response);
}
transactionControl.operationPrepared(new ModelController.OperationTransaction() {
public void commit() {
ref.set(ResultAction.KEEP);
}
public void rollback() {
ref.set(ResultAction.ROLLBACK);
}
}, primaryResponse, this);
}
resultAction = ref.get();
// Commit the persistence of any configuration changes
if (persistenceResource != null) {
if (resultAction == ResultAction.ROLLBACK) {
persistenceResource.rollback();
} else {
persistenceResource.commit();
}
}
} catch (Throwable t) {
toThrow = t;
resultAction = ResultAction.ROLLBACK;
} finally {
try {
executeResultHandlerPhase(toThrow);
} finally {
// For read-only ops, DoneStagePlaceholder can create cruft 'rolled-back' nodes. Remove them.
if (primaryResponse.has(ROLLED_BACK) && !primaryResponse.hasDefined(ROLLED_BACK)) {
primaryResponse.remove(ROLLED_BACK);
}
}
}
}
private void executeResultHandlerPhase(Throwable toThrow) {
respectInterruption = false;
try {
logAuditRecord();
emitNotifications();
} finally {
if (resultAction != ResultAction.KEEP) {
operationRollingBack();
}
// Execute the result handlers
activeStep.finalizeStep(toThrow);
}
}
@Override
public void emit(Notification notification) {
// buffer the notification and eventual missing description warning now
// but emit it and log the warning only when an operation is successful in emitNotifications()
checkUndefinedNotification(notification);
notifications.add(notification);
if (modifiedResourcesForModelValidation != null) {
//Hook for doing validation
String type = notification.getType();
switch (type) {
case ATTRIBUTE_VALUE_WRITTEN_NOTIFICATION:
case RESOURCE_ADDED_NOTIFICATION: {
PathAddress addr = notification.getSource();
synchronized (modifiedResourcesForModelValidation) {
if (!modifiedResourcesForModelValidation.contains(addr)) {
modifiedResourcesForModelValidation.add(addr);
}
}
break;
}
case RESOURCE_REMOVED_NOTIFICATION: {
PathAddress addr = notification.getSource();
synchronized (modifiedResourcesForModelValidation) {
if (modifiedResourcesForModelValidation.contains(addr)) {
modifiedResourcesForModelValidation.remove(addr);
}
}
break;
}
default:
//do nothing
}
}
}
private void emitNotifications() {
// emit notifications and log missing descriptions warnings only if the action is kept
if (resultAction != ResultAction.ROLLBACK) {
synchronized (missingNotificationDescriptionWarnings) {
for (String warning : missingNotificationDescriptionWarnings) {
ControllerLogger.ROOT_LOGGER.warn(warning);
}
missingNotificationDescriptionWarnings.clear();
}
synchronized (notifications) {
if (notifications.isEmpty()) {
return;
}
notificationSupport.emit(notifications.toArray(new Notification[notifications.size()]));
notifications.clear();
}
}
}
/**
* Check that each emitted notification is properly described by its source.
*/
private void checkUndefinedNotification(Notification notification) {
String type = notification.getType();
PathAddress source = notification.getSource();
Map<String, NotificationEntry> descriptions = getRootResourceRegistration().getNotificationDescriptions(source, true);
if (!descriptions.keySet().contains(type)) {
missingNotificationDescriptionWarnings.add(ControllerLogger.ROOT_LOGGER.notificationIsNotDescribed(type, source));
}
}
private void addBootFailureDescription() {
if (isBootOperation() && activeStep != null && activeStep.response.hasDefined(FAILURE_DESCRIPTION)) {
controller.addFailureDescription(activeStep.operation.clone(), activeStep.response.get(FAILURE_DESCRIPTION).clone());
}
}
abstract boolean isBootOperation();
private boolean canContinueProcessing() {
// Cancellation is detected via interruption.
if (Thread.currentThread().isInterrupted()) {
cancelled = true;
}
// Rollback when any of:
// 1. operation is cancelled
// 2. operation failed in model phase
// 3. operation failed in runtime/verify and rollback_on_fail is set
// 2. operation failed in domain phase
// 5. isRollbackOnly