/
OperationContextImpl.java
2620 lines (2290 loc) · 121 KB
/
OperationContextImpl.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
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.controller;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ACCESS_MECHANISM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ACTIVE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CALLER_THREAD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CALLER_TYPE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CANCELLED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXCLUSIVE_RUNNING_TIME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXECUTION_STATUS;
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.NILLABLE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NIL_SIGNIFICANT;
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.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REQUIRED;
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.RUNNING_TIME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_CONFIG;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.USER;
import static org.jboss.as.controller.logging.ControllerLogger.MGMT_OP_LOGGER;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.jboss.as.controller._private.OperationFailedRuntimeException;
import org.jboss.as.controller.access.Action;
import org.jboss.as.controller.access.Action.ActionEffect;
import org.jboss.as.controller.access.AuthorizationResult;
import org.jboss.as.controller.access.AuthorizationResult.Decision;
import org.jboss.as.controller.access.Caller;
import org.jboss.as.controller.access.Environment;
import org.jboss.as.controller.access.ResourceAuthorization;
import org.jboss.as.controller.access.ResourceNotAddressableException;
import org.jboss.as.controller.access.TargetAttribute;
import org.jboss.as.controller.access.TargetResource;
import org.jboss.as.controller.audit.AuditLogger;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.capability.registry.CapabilityId;
import org.jboss.as.controller.capability.registry.CapabilityResolutionContext;
import org.jboss.as.controller.capability.registry.CapabilityScope;
import org.jboss.as.controller.capability.registry.RegistrationPoint;
import org.jboss.as.controller.capability.registry.RuntimeCapabilityRegistration;
import org.jboss.as.controller.capability.registry.RuntimeCapabilityRegistry;
import org.jboss.as.controller.capability.registry.RuntimeRequirementRegistration;
import org.jboss.as.controller.client.MessageSeverity;
import org.jboss.as.controller.client.OperationAttachments;
import org.jboss.as.controller.client.OperationMessageHandler;
import org.jboss.as.controller.descriptions.DescriptionProvider;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
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.global.GlobalOperationHandlers;
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.DelegatingImmutableManagementResourceRegistration;
import org.jboss.as.controller.registry.DelegatingManagementResourceRegistration;
import org.jboss.as.controller.registry.ImmutableManagementResourceRegistration;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.as.controller.registry.PlaceholderResource;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.transform.ContextAttachments;
import org.jboss.as.core.security.AccessMechanism;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.AbstractServiceListener;
import org.jboss.msc.service.BatchServiceTarget;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceListener;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceNotFoundException;
import org.jboss.msc.service.ServiceRegistry;
import org.jboss.msc.service.ServiceRegistryException;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StabilityMonitor;
import org.jboss.msc.service.StartException;
import org.jboss.msc.value.ImmediateValue;
import org.jboss.msc.value.Value;
/**
* Operation context implementation.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
final class OperationContextImpl extends AbstractOperationContext {
private static final Object NULL = new Object();
private static final Set<Action.ActionEffect> ADDRESS = EnumSet.of(Action.ActionEffect.ADDRESS);
private static final Set<Action.ActionEffect> READ_CONFIG = EnumSet.of(Action.ActionEffect.READ_CONFIG);
private static final Set<Action.ActionEffect> READ_RUNTIME = EnumSet.of(Action.ActionEffect.READ_RUNTIME);
private static final Set<Action.ActionEffect> READ_WRITE_CONFIG = EnumSet.of(Action.ActionEffect.READ_CONFIG, Action.ActionEffect.WRITE_CONFIG);
private static final Set<Action.ActionEffect> READ_WRITE_RUNTIME = EnumSet.of(Action.ActionEffect.READ_RUNTIME, Action.ActionEffect.WRITE_RUNTIME);
private static final Set<Action.ActionEffect> WRITE_CONFIG = EnumSet.of(Action.ActionEffect.WRITE_CONFIG);
private static final Set<Action.ActionEffect> WRITE_RUNTIME = EnumSet.of(Action.ActionEffect.WRITE_RUNTIME);
private static final Set<Action.ActionEffect> ALL_READ_WRITE = EnumSet.of(Action.ActionEffect.READ_CONFIG, Action.ActionEffect.READ_RUNTIME, Action.ActionEffect.WRITE_CONFIG, Action.ActionEffect.WRITE_RUNTIME);
private final ModelControllerImpl modelController;
private final EnumSet<ContextFlag> contextFlags;
private final OperationMessageHandler messageHandler;
private final Map<ServiceName, ServiceController<?>> realRemovingControllers = new HashMap<ServiceName, ServiceController<?>>();
// protected by "realRemovingControllers"
private final Map<ServiceName, Step> removalSteps = new HashMap<ServiceName, Step>();
private final OperationAttachments attachments;
/** Tracks the addresses associated with writes to the model.
* We use a map with dummy values just to take advantage of ConcurrentHashMap */
private final Map<PathAddress, Object> affectsModel;
/** Resources that have had their services restarted, used by ALLOW_RESOURCE_SERVICE_RESTART This should be confined to a thread, so no sync needed */
private Map<PathAddress, Object> restartedResources = Collections.emptyMap();
private final ContextAttachments contextAttachments = new ContextAttachments(); private final Map<OperationId, AuthorizationResponseImpl> authorizations =
new ConcurrentHashMap<OperationId, AuthorizationResponseImpl>();
private final ModelNode blockingTimeoutConfig;
private volatile BlockingTimeout blockingTimeout;
private final long startTime = System.nanoTime();
private volatile long exclusiveStartTime = -1;
/** Tracks whether any steps have gotten write access to the resource tree */
private volatile boolean affectsResourceTree;
/** Tracks whether any steps have gotten write access to the management resource registration*/
private volatile boolean affectsResourceRegistration;
/** Tracks whether any steps have gotten write access to the capability registry */
private volatile boolean affectsCapabilityRegistry;
private volatile ModelControllerImpl.ManagementModelImpl managementModel;
private volatile ModelControllerImpl.ManagementModelImpl originalModel;
/** Tracks the relationship between domain resources and hosts and server groups */
private volatile HostServerGroupTracker hostServerGroupTracker;
/** Tracks whether any steps have gotten write access to the runtime */
private volatile boolean affectsRuntime;
/** The step that acquired the write lock */
private Step lockStep;
/** The step that acquired the container monitor */
private Step containerMonitorStep;
private volatile Boolean requiresModelUpdateAuthorization;
private volatile boolean readOnly = true;
/** Associates a requirement for a capability with the step that added it */
private final ConcurrentMap<RuntimeRequirementRegistration, Set<Step>> addedRequirements = new ConcurrentHashMap<>();
/** Associates a removed capability with the step that removed it */
private final ConcurrentMap<CapabilityId, Step> removedCapabilities = new ConcurrentHashMap<>();
/**
* Cache of resource descriptions generated during operation execution. Primarily intended for
* read-resource-description execution where the handler will ask for the description but the
* description may also be needed internally to support access control decisions.
*/
private final Map<PathAddress, ModelNode> resourceDescriptions =
Collections.synchronizedMap(new HashMap<PathAddress, ModelNode>());
private final Integer operationId;
private final String operationName;
private final ModelNode operationAddress;
private final AccessMechanism accessMechanism;
private final ActiveOperationResource activeOperationResource;
private final BooleanHolder done = new BooleanHolder();
private final boolean capabilitiesAlreadyBroken;
private final boolean partialModel;
private volatile ExecutionStatus executionStatus = ExecutionStatus.EXECUTING;
OperationContextImpl(final Integer operationId,
final String operationName, final ModelNode operationAddress,
final ModelControllerImpl modelController, final ProcessType processType,
final RunningMode runningMode, final EnumSet<ContextFlag> contextFlags,
final OperationMessageHandler messageHandler, final OperationAttachments attachments,
final ModelControllerImpl.ManagementModelImpl managementModel, final ModelController.OperationTransactionControl transactionControl,
final ControlledProcessState processState, final AuditLogger auditLogger, final boolean booting,
final HostServerGroupTracker hostServerGroupTracker,
final ModelNode blockingTimeoutConfig,
final AccessMechanism accessMechanism,
final NotificationSupport notificationSupport,
final boolean skipModelValidation,
final OperationStepHandler extraValidationStepHandler,
final boolean partialModel) {
super(processType, runningMode, transactionControl, processState, booting, auditLogger, notificationSupport,
modelController, skipModelValidation, extraValidationStepHandler);
this.operationId = operationId;
this.operationName = operationName;
this.operationAddress = operationAddress.isDefined()
? operationAddress : ModelControllerImpl.EMPTY_ADDRESS;
this.managementModel = managementModel;
this.originalModel = managementModel;
this.modelController = modelController;
this.messageHandler = messageHandler;
this.attachments = attachments;
this.affectsModel = booting ? new ConcurrentHashMap<PathAddress, Object>(16 * 16) : new HashMap<PathAddress, Object>(1);
this.contextFlags = contextFlags;
this.hostServerGroupTracker = hostServerGroupTracker;
this.blockingTimeoutConfig = blockingTimeoutConfig != null && blockingTimeoutConfig.isDefined() ? blockingTimeoutConfig : null;
this.activeOperationResource = new ActiveOperationResource();
this.accessMechanism = accessMechanism;
this.partialModel = partialModel;
if(runningMode == RunningMode.ADMIN_ONLY) {
boolean hostXmlOnly = booting && !processType.isServer() && partialModel;
CapabilityRegistry.CapabilityValidation validation = managementModel.validateCapabilityRegistry(true, hostXmlOnly);
this.capabilitiesAlreadyBroken = !validation.isValid();
} else {
this.capabilitiesAlreadyBroken = false;
}
}
public InputStream getAttachmentStream(final int index) {
if (attachments == null) {
throw new ArrayIndexOutOfBoundsException(index);
}
return attachments.getInputStreams().get(index);
}
public int getAttachmentStreamCount() {
return attachments == null ? 0 : attachments.getInputStreams().size();
}
@Override
boolean stageCompleted(Stage stage) {
return (stage != Stage.MODEL || validateCapabilities());
}
ModelControllerImpl.ManagementModelImpl getManagementModel() {
return managementModel;
}
private boolean validateCapabilities() {
// Validate that all required capabilities are available and fail any steps that broke this
boolean hostXmlOnly = isBooting() && !getProcessType().isServer() && partialModel;
CapabilityRegistry.CapabilityValidation validation = managementModel.validateCapabilityRegistry(false, hostXmlOnly);
boolean ok = validation.isValid();
final boolean adminOnly = this.getRunningMode() == RunningMode.ADMIN_ONLY;
//if we are in admin only mode and everything is already broken then we don't care about failures
final boolean ignoreFailures = adminOnly && (capabilitiesAlreadyBroken || isBooting());
if (!ok) {
boolean failureRecorded = false;
StringBuilder unexplainedProblem = null;
// Whether we care about context depends on whether we are a server
boolean ignoreContext = getProcessType().isServer();
CapabilityResolutionContext resolutionContext = validation.getCapabilityResolutionContext();
Map<CapabilityId, Set<RuntimeRequirementRegistration>> missing = validation.getMissingRequirements();
Map<Step, Set<CapabilityId>> missingForStep = new HashMap<>();
for (Map.Entry<CapabilityId, Set<RuntimeRequirementRegistration>> entry : missing.entrySet()) {
CapabilityId required = entry.getKey();
// See if any step removed this capability
Step guilty = findCapabilityRemovalStep(required, ignoreContext, resolutionContext);
if (guilty != null) {
// Change the response for the step to mark as failed
StringBuilder msg = new StringBuilder();
if (ignoreContext) {
msg = msg.append(ControllerLogger.ROOT_LOGGER.cannotRemoveRequiredCapability(required.getName()));
} else {
msg = msg.append(ControllerLogger.ROOT_LOGGER.cannotRemoveRequiredCapabilityInContext(required.getName(), required.getScope().getName()));
}
for (RuntimeRequirementRegistration reg : entry.getValue()) {
RegistrationPoint rp = reg.getOldestRegistrationPoint();
if (rp.getAttribute() == null) {
msg = msg.append('\n').append(ControllerLogger.ROOT_LOGGER.requirementPointSimple(reg.getDependentName(), rp.getAddress().toCLIStyleString()));
} else {
msg = msg.append('\n').append(ControllerLogger.ROOT_LOGGER.requirementPointFull(reg.getDependentName(), rp.getAttribute(), rp.getAddress().toCLIStyleString()));
}
}
String msgString = msg.toString();
if(!ignoreFailures) {
guilty.response.get(FAILURE_DESCRIPTION).set(msgString);
}
failureRecorded = true;
if (isBooting() || ignoreFailures) { // this is unlikely for this block since boot wouldn't remove, but let's be thorough.
ControllerLogger.ROOT_LOGGER.error(guilty.address.toCLIStyleString() + " -- " + msgString);
}
} else {
for (RuntimeRequirementRegistration reqReq : entry.getValue()) {
// Problem wasn't a capability removal.
// See what step(s) added this requirement
Set<Step> bereft = addedRequirements.get(reqReq);
if (bereft != null && bereft.size() > 0) {
for (Step step : bereft) {
Set<CapabilityId> set = missingForStep.get(step);
if (set == null) {
set = new HashSet<>();
missingForStep.put(step, set);
}
set.add(required);
}
} else {
if (unexplainedProblem == null) {
unexplainedProblem = new StringBuilder(ControllerLogger.ROOT_LOGGER.requiredCapabilityMissing());
}
String formattedCapability = ignoreContext
? ControllerLogger.ROOT_LOGGER.formattedCapabilityName(reqReq.getRequiredName())
: ControllerLogger.ROOT_LOGGER.formattedCapabilityId(reqReq.getRequiredName(), reqReq.getDependentContext().getName());
Set<PathAddress> possiblePoints = managementModel.getCapabilityRegistry().getPossibleProviderPoints(reqReq.getDependentId());
appendPossibleProviderPoints(unexplainedProblem, formattedCapability, possiblePoints);
}
}
}
}
// Change the response for all steps that added an unfulfilled requirement
for (Map.Entry<Step, Set<CapabilityId>> entry : missingForStep.entrySet()) {
Step step = entry.getKey();
ModelNode response = step.response;
// only overwrite reponse failure-description if there isn't one
StringBuilder msg = response.hasDefined(FAILURE_DESCRIPTION)
? null
: new StringBuilder(ControllerLogger.ROOT_LOGGER.requiredCapabilityMissing());
StringBuilder bootMsg = isBooting() || ignoreFailures
? new StringBuilder(ControllerLogger.ROOT_LOGGER.requiredCapabilityMissing(step.address.toCLIStyleString()))
: null;
for (CapabilityId id : entry.getValue()) {
String formattedCapability = ignoreContext
? ControllerLogger.ROOT_LOGGER.formattedCapabilityName(id.getName())
: ControllerLogger.ROOT_LOGGER.formattedCapabilityId(id.getName(), id.getScope().getName());
Set<PathAddress> possiblePoints = managementModel.getCapabilityRegistry().getPossibleProviderPoints(id);
if (msg != null) {
msg = appendPossibleProviderPoints(msg, formattedCapability, possiblePoints);
}
if (bootMsg != null) {
bootMsg = appendPossibleProviderPoints(bootMsg, formattedCapability, possiblePoints);
}
}
if (msg != null) {
if(!ignoreFailures) {
response.get(FAILURE_DESCRIPTION).set(msg.toString());
}
failureRecorded = true;
}
if (bootMsg != null) {
ControllerLogger.ROOT_LOGGER.error(bootMsg.toString());
}
}
if (!ignoreContext) {
for (RuntimeRequirementRegistration reg : validation.getInconsistentRequirements()) {
// See what step(s) added this requirement
Set<Step> inconsistent = addedRequirements.get(reg);
if (inconsistent != null && inconsistent.size() > 0) {
for (Step step : inconsistent) {
ModelNode response = step.response;
String depConName = reg.getDependentContext().getName();
// only overwrite reponse failure-description if there isn't one
if (!response.hasDefined(FAILURE_DESCRIPTION)) {
if(!(adminOnly && isBooting())) {
response.get(FAILURE_DESCRIPTION).set(ControllerLogger.ROOT_LOGGER.inconsistentCapabilityContexts(reg.getRequiredName(),
reg.getDependentName(), depConName, depConName));
}
failureRecorded = true;
}
if (isBooting()) {
ControllerLogger.ROOT_LOGGER.inconsistentCapabilityContexts(reg.getDependentName(),
depConName, step.address.toCLIStyleString(), reg.getRequiredName(), depConName);
}
}
} else {
if (unexplainedProblem == null) {
unexplainedProblem = new StringBuilder();
} else {
unexplainedProblem.append('\n');
}
String depConName = reg.getDependentContext().getName();
unexplainedProblem.append(ControllerLogger.ROOT_LOGGER.inconsistentCapabilityContexts(reg.getRequiredName(),
reg.getDependentName(), depConName, depConName));
}
}
}
// If we didn't record a failure on any response, put one on the initial response
if (!failureRecorded && unexplainedProblem != null && !initialResponse.hasDefined(FAILURE_DESCRIPTION)) {
if(!ignoreFailures) {
initialResponse.get(FAILURE_DESCRIPTION).set(unexplainedProblem.toString());
}
if(isBooting() || ignoreFailures) {
ControllerLogger.ROOT_LOGGER.error(unexplainedProblem);
}
}
}
return ok || ignoreFailures;
}
private static StringBuilder appendPossibleProviderPoints(StringBuilder sb, String formattedCapability, Set<PathAddress> possible){
//"you wanted X and it doesn't exist; here's where you can add X"
sb = sb.append(System.lineSeparator()).append(formattedCapability);
if (possible.isEmpty()){
return sb.append(ControllerLogger.ROOT_LOGGER.noKnownProviderPoints());
}
StringBuffer points = new StringBuffer();
for (PathAddress c: possible){
points = points.append(System.lineSeparator()).append("\t\t").append(c.toCLIStyleString());
}
return sb.append(ControllerLogger.ROOT_LOGGER.possibleCapabilityProviderPoints(points.toString()));
}
private Step findCapabilityRemovalStep(CapabilityId missingRequirement, boolean ignoreContext, CapabilityResolutionContext resolutionContext) {
Step result = removedCapabilities.get(missingRequirement);
if (result == null && !ignoreContext) {
String missingName = missingRequirement.getName();
for (Map.Entry<CapabilityId, Step> entry : removedCapabilities.entrySet()) {
CapabilityId removedId = entry.getKey();
if (missingName.equals(removedId.getName())
&& removedId.getScope().canSatisfyRequirement(missingRequirement.getName(), missingRequirement.getScope(), resolutionContext)) {
result = entry.getValue();
break;
}
}
}
return result;
}
@Override
void awaitServiceContainerStability() throws InterruptedException, TimeoutException {
if (affectsRuntime) {
MGMT_OP_LOGGER.debugf("Entered VERIFY stage; waiting for service container to settle");
long timeout = getBlockingTimeout().getBlockingTimeout();
ExecutionStatus originalExecutionStatus = executionStatus;
try {
// First wait until any removals we've initiated have begun processing, otherwise
// the ContainerStateMonitor may not have gotten the notification causing it to untick
executionStatus = ExecutionStatus.AWAITING_STABILITY;
waitForRemovals();
ContainerStateMonitor.ContainerStateChangeReport changeReport =
modelController.awaitContainerStateChangeReport(timeout, TimeUnit.MILLISECONDS);
// If any services are missing, add a verification handler to see if we caused it
if (changeReport != null && !changeReport.getMissingServices().isEmpty()) {
ServiceRemovalVerificationHandler removalVerificationHandler = new ServiceRemovalVerificationHandler(changeReport);
addStep(new ModelNode(), new ModelNode(), PathAddress.EMPTY_ADDRESS, removalVerificationHandler, Stage.VERIFY);
}
} catch (TimeoutException te) {
getBlockingTimeout().timeoutDetected();
// Deliberate log and throw; we want to log this but the caller method passes a slightly different
// message to the user as part of the operation response
MGMT_OP_LOGGER.timeoutExecutingOperation(timeout / 1000, containerMonitorStep.operationId.name, containerMonitorStep.address);
throw te;
} finally {
executionStatus = originalExecutionStatus;
}
}
}
@Override
protected void waitForRemovals() throws InterruptedException, TimeoutException {
if (affectsRuntime && !cancelled) {
synchronized (realRemovingControllers) {
long waitTime = getBlockingTimeout().getBlockingTimeout();
long end = System.currentTimeMillis() + waitTime;
boolean wait = !realRemovingControllers.isEmpty() && !cancelled;
while (wait && waitTime > 0) {
realRemovingControllers.wait(waitTime);
wait = !realRemovingControllers.isEmpty() && !cancelled;
waitTime = end - System.currentTimeMillis();
}
if (wait) {
getBlockingTimeout().timeoutDetected();
throw new TimeoutException();
}
}
}
}
@Override
ConfigurationPersister.PersistenceResource createPersistenceResource() throws ConfigurationPersistenceException {
return modelController.writeModel(managementModel, affectsModel.keySet());
}
@Override
void operationRollingBack() {
modelController.discardModel(managementModel);
}
void publishCapabilityRegistry() {
modelController.publishCapabilityRegistry(managementModel);
}
@Override
public boolean isRollbackOnRuntimeFailure() {
return contextFlags.contains(ContextFlag.ROLLBACK_ON_FAIL);
}
@Override
public boolean isResourceServiceRestartAllowed() {
return contextFlags.contains(ContextFlag.ALLOW_RESOURCE_SERVICE_RESTART);
}
public ManagementResourceRegistration getResourceRegistrationForUpdate() {
return getMutableResourceRegistration(activeStep.address);
}
private ManagementResourceRegistration getMutableResourceRegistration(PathAddress absoluteAddress) {
readOnly = false;
assert isControllingThread();
// Don't require model as some handlers do runtime registration due to needing to see
// what's exposed by a runtime service
//checkStageModel(currentStage);
assertNotComplete(currentStage);
authorize(false, READ_WRITE_CONFIG);
ensureLocalManagementResourceRegistration();
ManagementResourceRegistration mrr = managementModel.getRootResourceRegistration();
ManagementResourceRegistration delegate = absoluteAddress == null ? mrr : mrr.getSubModel(absoluteAddress);
return new DescriptionCachingResourceRegistration(delegate, absoluteAddress);
}
@Override
public ImmutableManagementResourceRegistration getResourceRegistration() {
assert isControllingThread();
assertNotComplete(currentStage);
authorize(false, Collections.<ActionEffect>emptySet());
final PathAddress address = activeStep.address;
ImmutableManagementResourceRegistration delegate = managementModel.getRootResourceRegistration().getSubModel(address);
return delegate == null ? null : new DescriptionCachingImmutableResourceRegistration(delegate, address);
}
@Override
public ImmutableManagementResourceRegistration getRootResourceRegistration() {
assert isControllingThread();
assertNotComplete(currentStage);
ImmutableManagementResourceRegistration delegate = managementModel.getRootResourceRegistration();
return delegate == null ? null : new DescriptionCachingImmutableResourceRegistration(delegate, PathAddress.EMPTY_ADDRESS);
}
@Override
public ServiceRegistry getServiceRegistry(final boolean modify) throws UnsupportedOperationException {
return getServiceRegistry(modify, this.activeStep);
}
/**
* Gets a service registry that will ensure
* {@link org.jboss.msc.service.ServiceController#setMode(org.jboss.msc.service.ServiceController.Mode) changes to the mode}
* of registered services will result in subsequent verification of service stability.
*
* @param modify {@code true} if the caller intends to modify state
* @param registryActiveStep the {@link org.jboss.as.controller.AbstractOperationContext.Step} that encapsulates
* the {@link org.jboss.as.controller.OperationStepHandler} that is making the call.
* @return the service registry
*/
ServiceRegistry getServiceRegistry(final boolean modify, final Step registryActiveStep) {
if (modify) {
readOnly = false;
}
assert isControllingThread();
Stage currentStage = this.currentStage;
assertNotComplete(currentStage);
// TODO why do we allow Stage.MODEL?
if (! (!modify || currentStage == Stage.RUNTIME || currentStage == Stage.MODEL || currentStage == Stage.VERIFY || isRollingBack())) {
throw ControllerLogger.ROOT_LOGGER.serviceRegistryRuntimeOperationsOnly();
}
authorize(false, modify ? READ_WRITE_RUNTIME : READ_RUNTIME);
if (modify) {
ensureWriteLockForRuntime();
}
return new OperationContextServiceRegistry(modelController.getServiceRegistry(), registryActiveStep);
}
public ServiceController<?> removeService(final ServiceName name) throws UnsupportedOperationException {
readOnly = false;
assert isControllingThread();
if (!isRuntimeChangeAllowed(currentStage)) {
throw ControllerLogger.ROOT_LOGGER.serviceRemovalRuntimeOperationsOnly();
}
authorize(false, WRITE_RUNTIME);
ensureWriteLockForRuntime();
ServiceController<?> controller = modelController.getServiceRegistry().getService(name);
if (controller != null) {
doRemove(controller);
}
return controller;
}
@Override
public boolean markResourceRestarted(PathAddress resource, Object owner) {
if (restartedResources.containsKey(resource) ) {
return false;
}
if (restartedResources == Collections.EMPTY_MAP) {
restartedResources = new HashMap<PathAddress, Object>();
}
restartedResources.put(resource, owner);
return true;
}
@Override
public boolean revertResourceRestarted(PathAddress resource, Object owner) {
if (restartedResources.get(resource) == owner) {
restartedResources.remove(resource);
return true;
}
return false;
}
public void removeService(final ServiceController<?> controller) throws UnsupportedOperationException {
readOnly = false;
assert isControllingThread();
if (!isRuntimeChangeAllowed(currentStage)) {
throw ControllerLogger.ROOT_LOGGER.serviceRemovalRuntimeOperationsOnly();
}
authorize(false, WRITE_RUNTIME);
ensureWriteLockForRuntime();
if (controller != null) {
doRemove(controller);
}
}
private void doRemove(final ServiceController<?> controller) {
final Step removalStep = activeStep;
removalStep.hasRemovals = true;
controller.addListener(new AbstractServiceListener<Object>() {
public void listenerAdded(final ServiceController<?> controller) {
synchronized (realRemovingControllers) {
realRemovingControllers.put(controller.getName(), controller);
controller.setMode(ServiceController.Mode.REMOVE);
}
}
public void transition(final ServiceController<?> controller, final ServiceController.Transition transition) {
switch (transition) {
case REMOVING_to_REMOVED:
case REMOVING_to_DOWN: {
synchronized (realRemovingControllers) {
ServiceName name = controller.getName();
if (realRemovingControllers.get(name) == controller) {
realRemovingControllers.remove(name);
removalSteps.put(name, removalStep);
realRemovingControllers.notifyAll();
}
}
break;
}
}
}
});
}
@Override
public ServiceTarget getServiceTarget() throws UnsupportedOperationException {
return getServiceTarget(activeStep);
}
/**
* Gets a service target that will ensure that any
* {@link org.jboss.msc.service.ServiceTarget#addService(org.jboss.msc.service.ServiceName, org.jboss.msc.service.Service)
* added services} will be tracked for subsequent verification of service stability.
*
* @param targetActiveStep the {@link org.jboss.as.controller.AbstractOperationContext.Step} that encapsulates
* the {@link org.jboss.as.controller.OperationStepHandler} that is making the call.
* @return the service target
*/
ServiceTarget getServiceTarget(Step targetActiveStep) throws UnsupportedOperationException {
readOnly = false;
assert isControllingThread();
if (!isRuntimeChangeAllowed(currentStage)) {
throw ControllerLogger.ROOT_LOGGER.serviceTargetRuntimeOperationsOnly();
}
ensureWriteLockForRuntime();
return new ContextServiceTarget(targetActiveStep);
}
Resource.ResourceEntry getActiveOperationResource() {
return activeOperationResource;
}
private void takeWriteLock() {
if (lockStep == null) {
if (currentStage == Stage.DONE) {
throw ControllerLogger.ROOT_LOGGER.invalidModificationAfterCompletedStep();
}
ExecutionStatus originalStatus = executionStatus;
try {
executionStatus = ExecutionStatus.AWAITING_OTHER_OPERATION;
// BES 2014/04/22 Ignore blocking timeout here. We risk some bug causing the
// lock to never be released. But we gain multiple ops being able to wait until they get
// a chance to run with no need to guess how long op 2 will take so we can
// let op 3 block for the time needed for both 1 and 2
// int timeout = blockingTimeout.getBlockingTimeout();
// if (timeout < 1) {
modelController.acquireLock(operationId, respectInterruption);
// } else {
// // Wait longer than the standard amount to get a chance to execute
// // after whatever was holding the lock times out
// timeout += 10;
// if (!modelController.acquireLock(operationId, respectInterruption, timeout)) {
// throw MESSAGES.operationTimeoutAwaitingControllerLock(timeout);
// }
// }
exclusiveStartTime = System.nanoTime();
lockStep = activeStep;
} catch (InterruptedException e) {
cancelled = true;
Thread.currentThread().interrupt();
throw ControllerLogger.ROOT_LOGGER.operationCancelledAsynchronously();
} finally {
executionStatus = originalStatus;
}
}
}
private void ensureWriteLockForRuntime() {
if (!affectsRuntime) {
takeWriteLock();
affectsRuntime = true;
if (containerMonitorStep == null) {
if (currentStage == Stage.DONE) {
throw ControllerLogger.ROOT_LOGGER.invalidModificationAfterCompletedStep();
}
containerMonitorStep = activeStep;
int timeout = getBlockingTimeout().getBlockingTimeout();
ExecutionStatus origStatus = executionStatus;
try {
executionStatus = ExecutionStatus.AWAITING_STABILITY;
modelController.awaitContainerStability(timeout, TimeUnit.MILLISECONDS, respectInterruption);
} catch (InterruptedException e) {
if (resultAction != ResultAction.ROLLBACK) {
// We're not on the way out, so we've been cancelled on the way in
cancelled = true;
}
Thread.currentThread().interrupt();
throw ControllerLogger.ROOT_LOGGER.operationCancelledAsynchronously();
} catch (TimeoutException te) {
getBlockingTimeout().timeoutDetected();
// This is the first step trying to await stability for this op, so if it's
// unstable some previous step must have messed it up and it can't recover.
// So this process must restart.
// The previous op should have set this in {@code releaseStepLocks}; doing it again
// here is just a 2nd line of defense
processState.setRestartRequired();// don't use our restartRequired() method as this is not reversible in rollback
// Deliberate log and throw; we want this logged, we need to notify user, and I want slightly
// different messages for both so just throwing a RuntimeException to get the automatic handling
// in AbstractOperationContext.executeStep is not what I wanted
ControllerLogger.MGMT_OP_LOGGER.timeoutAwaitingInitialStability(timeout / 1000, activeStep.operationId.name, activeStep.operationId.address);
setRollbackOnly();
throw new OperationFailedRuntimeException(ControllerLogger.ROOT_LOGGER.timeoutAwaitingInitialStability());
} finally {
executionStatus = origStatus;
}
}
}
}
public Resource readResource(final PathAddress requestAddress) {
return readResource(requestAddress, true);
}
public Resource readResource(final PathAddress requestAddress, final boolean recursive) {
final PathAddress address = activeStep.address.append(requestAddress);
return readResourceFromRoot(address, recursive);
}
public Resource readResourceFromRoot(final PathAddress address) {
return readResourceFromRoot(address, true);
}
public Resource readResourceFromRoot(final PathAddress address, final boolean recursive) {
assert isControllingThread();
assertNotComplete(currentStage);
//Clone the operation to preserve all the headers
ModelNode operation = activeStep.operation.clone();
operation.get(OP).set(ReadResourceHandler.DEFINITION.getName());
operation.get(OP_ADDR).set(address.toModelNode());
OperationId opId = new OperationId(operation);
AuthorizationResult authResult = authorize(opId, operation, false, READ_CONFIG);
if (authResult.getDecision() == AuthorizationResult.Decision.DENY) {
// See if the problem was addressability
AuthorizationResult addressResult = authorize(opId, operation, false, ADDRESS);
if (addressResult.getDecision() == AuthorizationResult.Decision.DENY) {
throw new ResourceNotAddressableException(activeStep.address);
}
throw ControllerLogger.ROOT_LOGGER.unauthorized(activeStep.operationId.name, activeStep.address, authResult.getExplanation());
}
return readResourceFromRoot(managementModel, address, recursive);
}
@Override
Resource readResourceFromRoot(ManagementModel managementModel, PathAddress address, boolean recursive) {
//
// TODO double check authorization checks for this!
//
Resource model = managementModel.getRootResource();
final Iterator<PathElement> iterator = address.iterator();
while(iterator.hasNext()) {
final PathElement element = iterator.next();
// Allow wildcard navigation for the last element
if(element.isWildcard() && ! iterator.hasNext()) {
final Set<Resource.ResourceEntry> children = model.getChildren(element.getKey());
if(children.isEmpty()) {
final PathAddress parent = address.subAddress(0, address.size() -1);
final Set<String> childrenTypes = managementModel.getRootResourceRegistration().getChildNames(parent);
if(! childrenTypes.contains(element.getKey())) {
throw ControllerLogger.ROOT_LOGGER.managementResourceNotFound(address);
}
// Return an empty model
return Resource.Factory.create();
}
model = Resource.Factory.create();
for(final Resource.ResourceEntry entry : children) {
model.registerChild(entry.getPathElement(), entry);
}
} else {
model = requireChild(model, element, address);
}
}
if(recursive) {
return model.clone();
} else {
final Resource copy = Resource.Factory.create();
copy.writeModel(model.getModel());
for(final String childType : model.getChildTypes()) {
for(final Resource.ResourceEntry child : model.getChildren(childType)) {
copy.registerChild(child.getPathElement(), PlaceholderResource.INSTANCE);
}
}
return copy;
}
}
public Resource readResourceForUpdate(PathAddress requestAddress) {
readOnly = false;
assert isControllingThread();
assertStageModel(currentStage);
final PathAddress address = activeStep.address.append(requestAddress);
// WFLY-3017 See if this write means a persistent config change
// For speed, we assume all calls during boot relate to persistent config
boolean runtimeOnly = !isBooting() && isResourceRuntimeOnly(address);
if (!runtimeOnly) {
rejectUserDomainServerUpdates();
}
checkHostServerGroupTracker(address);
authorize(false, runtimeOnly ? READ_WRITE_RUNTIME : READ_WRITE_CONFIG);
ensureLocalRootResource();
affectsModel.put(address, NULL);
Resource resource = this.managementModel.getRootResource();
for (PathElement element : address) {
if (element.isMultiTarget()) {
throw ControllerLogger.ROOT_LOGGER.cannotWriteTo("*");
}
resource = requireChild(resource, element, address);
}
return resource;
}
private boolean isResourceRuntimeOnly(PathAddress fullAddress) {
Resource resource = this.managementModel.getRootResource();
for (Iterator<PathElement> it = fullAddress.iterator(); it.hasNext() && resource != null;) {
PathElement element = it.next();
if (element.isMultiTarget()) {
resource = null;
} else {
resource = resource.getChild(element);
}
}
if (resource != null) {
return resource.isRuntime();
}
// No resource -- op will eventually fail
ImmutableManagementResourceRegistration mrr = managementModel.getRootResourceRegistration().getSubModel(fullAddress);
return mrr != null && mrr.isRuntimeOnly();
}
@Override
public Resource getOriginalRootResource() {
// TODO restrict
return originalModel.getRootResource().clone();
}
@Override
public Resource createResource(PathAddress relativeAddress) {
return createResourceInternal(relativeAddress, -1);
}
private Resource createResourceInternal(PathAddress relativeAddress, int index) throws UnsupportedOperationException {
ImmutableManagementResourceRegistration current = getResourceRegistration();
ImmutableManagementResourceRegistration mrr = relativeAddress == PathAddress.EMPTY_ADDRESS ? current : current.getSubModel(relativeAddress);
final Resource toAdd = Resource.Factory.create(mrr.isRuntimeOnly());
addResourceInternal(relativeAddress, index, toAdd);
return toAdd;
}
@Override
public void addResource(PathAddress relativeAddress, Resource toAdd) {
addResourceInternal(relativeAddress, -1, toAdd);
}
@Override
public void addResource(PathAddress relativeAddress, int index, Resource toAdd) {
assert index >= 0 : "index must be 0 or greater";
addResourceInternal(relativeAddress, index, toAdd);
}
private void addResourceInternal(PathAddress relativeAddress, int index, Resource toAdd) {
readOnly = false;
assert isControllingThread();
assertStageModel(currentStage);
final PathAddress absoluteAddress = activeStep.address.append(relativeAddress);
if (absoluteAddress.size() == 0) {
throw ControllerLogger.ROOT_LOGGER.duplicateResourceAddress(absoluteAddress);
}
boolean runtimeOnly = toAdd.isRuntime();
if (!runtimeOnly) {
// Check for user updates to a domain server model
rejectUserDomainServerUpdates();
}
checkHostServerGroupTracker(absoluteAddress);
authorizeAdd(runtimeOnly);
ensureLocalRootResource();
affectsModel.put(absoluteAddress, NULL);
Resource model = this.managementModel.getRootResource();
final Iterator<PathElement> i = absoluteAddress.iterator();
while (i.hasNext()) {
final PathElement element = i.next();
if (element.isMultiTarget()) {
throw ControllerLogger.ROOT_LOGGER.cannotWriteTo("*");
}
if (! i.hasNext()) {
final String key = element.getKey();
if(model.hasChild(element)) {
throw ControllerLogger.ROOT_LOGGER.duplicateResourceAddress(absoluteAddress);
} else {
final PathAddress parent = absoluteAddress.subAddress(0, absoluteAddress.size() -1);