2 * Copyright (c) 2017 Pantheon Technologies, s.r.o. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.yang.parser.rfc7950.stmt.deviate;
10 import com.google.common.collect.ImmutableList;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.collect.ImmutableSet;
13 import com.google.common.collect.Iterables;
14 import com.google.common.collect.Maps;
15 import com.google.common.collect.SetMultimap;
16 import java.util.Arrays;
17 import java.util.Collection;
18 import java.util.List;
19 import java.util.Objects;
21 import org.opendaylight.yangtools.yang.common.Empty;
22 import org.opendaylight.yangtools.yang.common.QNameModule;
23 import org.opendaylight.yangtools.yang.common.YangVersion;
24 import org.opendaylight.yangtools.yang.model.api.DeviateKind;
25 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
26 import org.opendaylight.yangtools.yang.model.api.meta.DeclarationReference;
27 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
29 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
30 import org.opendaylight.yangtools.yang.model.api.stmt.DeviateEffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.DeviateStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
33 import org.opendaylight.yangtools.yang.model.ri.stmt.DeclaredStatementDecorators;
34 import org.opendaylight.yangtools.yang.model.ri.stmt.DeclaredStatements;
35 import org.opendaylight.yangtools.yang.model.ri.stmt.EffectiveStatements;
36 import org.opendaylight.yangtools.yang.parser.api.YangParserConfiguration;
37 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
38 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.BoundStmtCtx;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
54 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
55 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 abstract class AbstractDeviateStatementSupport
60 extends AbstractStatementSupport<DeviateKind, DeviateStatement, DeviateEffectiveStatement> {
61 private static final Logger LOG = LoggerFactory.getLogger(AbstractDeviateStatementSupport.class);
63 private static final SubstatementValidator DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR =
64 SubstatementValidator.builder(YangStmtMapping.DEVIATE).build();
66 private static final SubstatementValidator DEVIATE_ADD_SUBSTATEMENT_VALIDATOR =
67 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
68 .addOptional(YangStmtMapping.CONFIG)
69 .addOptional(YangStmtMapping.DEFAULT)
70 .addOptional(YangStmtMapping.MANDATORY)
71 .addOptional(YangStmtMapping.MAX_ELEMENTS)
72 .addOptional(YangStmtMapping.MIN_ELEMENTS)
73 .addAny(YangStmtMapping.MUST)
74 .addAny(YangStmtMapping.UNIQUE)
75 .addOptional(YangStmtMapping.UNITS)
78 private static final SubstatementValidator DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR =
79 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
80 .addOptional(YangStmtMapping.CONFIG)
81 .addOptional(YangStmtMapping.DEFAULT)
82 .addOptional(YangStmtMapping.MANDATORY)
83 .addOptional(YangStmtMapping.MAX_ELEMENTS)
84 .addOptional(YangStmtMapping.MIN_ELEMENTS)
85 .addOptional(YangStmtMapping.TYPE)
86 .addOptional(YangStmtMapping.UNITS)
89 private static final SubstatementValidator DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR =
90 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
91 .addOptional(YangStmtMapping.DEFAULT)
92 .addAny(YangStmtMapping.MUST)
93 .addAny(YangStmtMapping.UNIQUE)
94 .addOptional(YangStmtMapping.UNITS)
97 private static final ImmutableMap<String, DeviateKind> KEYWORD_TO_DEVIATE_MAP =
98 Maps.uniqueIndex(Arrays.asList(DeviateKind.values()), DeviateKind::getKeyword);
100 private static final ImmutableSet<YangStmtMapping> SINGLETON_STATEMENTS = ImmutableSet.of(
101 YangStmtMapping.UNITS, YangStmtMapping.CONFIG, YangStmtMapping.MANDATORY,
102 YangStmtMapping.MIN_ELEMENTS, YangStmtMapping.MAX_ELEMENTS);
104 private static final ImmutableSet<YangStmtMapping> IMPLICIT_STATEMENTS = ImmutableSet.of(YangStmtMapping.CONFIG,
105 YangStmtMapping.MANDATORY, YangStmtMapping.MAX_ELEMENTS, YangStmtMapping.MIN_ELEMENTS);
107 AbstractDeviateStatementSupport(final YangParserConfiguration config) {
108 // Note: we are performing our own validation based on deviate kind.
109 // TODO: perhaps we should do argumentSpecificSupport?
110 super(YangStmtMapping.DEVIATE, StatementPolicy.contextIndependent(), config, null);
114 public final DeviateKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
115 return SourceException.throwIfNull(KEYWORD_TO_DEVIATE_MAP.get(value), ctx,
116 "String '%s' is not valid deviate argument", value);
120 public final void onFullDefinitionDeclared(
121 final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx) {
122 final DeviateKind deviateKind = deviateStmtCtx.argument();
123 getSubstatementValidatorForDeviate(deviateKind).validate(deviateStmtCtx);
125 final SchemaNodeIdentifier deviationTarget =
126 (SchemaNodeIdentifier) deviateStmtCtx.coerceParentContext().argument();
128 if (!isDeviationSupported(deviateStmtCtx, deviationTarget)) {
132 final ModelActionBuilder deviateAction = deviateStmtCtx.newInferenceAction(
133 ModelProcessingPhase.EFFECTIVE_MODEL);
135 final Prerequisite<StmtContext<DeviateKind, DeviateStatement,
136 DeviateEffectiveStatement>> sourceCtxPrerequisite =
137 deviateAction.requiresCtx(deviateStmtCtx, ModelProcessingPhase.EFFECTIVE_MODEL);
139 final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> targetCtxPrerequisite =
140 deviateAction.mutatesEffectiveCtxPath(deviateStmtCtx.getRoot(),
141 SchemaTreeNamespace.class, deviationTarget.getNodeIdentifiers());
143 deviateAction.apply(new InferenceAction() {
145 public void apply(final InferenceContext ctx) {
146 if (!deviateStmtCtx.isSupportedToBuildEffective()) {
147 // We are not building effective model, hence we should not be performing any effects
151 final var sourceNodeStmtCtx = sourceCtxPrerequisite.resolve(ctx);
152 final var targetNodeStmtCtx = targetCtxPrerequisite.resolve(ctx);
154 switch (deviateKind) {
156 // FIXME: this can be short-circuited without an inference action
157 targetNodeStmtCtx.setUnsupported();
160 performDeviateAdd(sourceNodeStmtCtx, targetNodeStmtCtx);
163 performDeviateReplace(sourceNodeStmtCtx, targetNodeStmtCtx);
166 performDeviateDelete(sourceNodeStmtCtx, targetNodeStmtCtx);
169 throw new IllegalStateException("Unsupported deviate " + deviateKind);
174 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
175 throw new InferenceException(deviateStmtCtx.coerceParentContext(), "Deviation target '%s' not found.",
180 public void prerequisiteUnavailable(final Prerequisite<?> unavail) {
181 if (targetCtxPrerequisite.equals(unavail)) {
182 deviateStmtCtx.setUnsupported();
184 prerequisiteFailed(List.of(unavail));
191 public String internArgument(final String rawArgument) {
192 if ("add".equals(rawArgument)) {
194 } else if ("delete".equals(rawArgument)) {
196 } else if ("replace".equals(rawArgument)) {
198 } else if ("not-supported".equals(rawArgument)) {
199 return "not-supported";
206 protected final DeviateStatement createDeclared(final BoundStmtCtx<DeviateKind> ctx,
207 final ImmutableList<DeclaredStatement<?>> substatements) {
208 return DeclaredStatements.createDeviate(ctx.getArgument(), substatements);
212 protected final DeviateStatement attachDeclarationReference(final DeviateStatement stmt,
213 final DeclarationReference reference) {
214 return DeclaredStatementDecorators.decorateDeviate(stmt, reference);
218 protected final DeviateEffectiveStatement createEffective(final Current<DeviateKind, DeviateStatement> stmt,
219 final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
220 return EffectiveStatements.createDeviate(stmt.declared(), substatements);
223 protected SubstatementValidator getSubstatementValidatorForDeviate(final DeviateKind deviateKind) {
224 switch (deviateKind) {
226 return DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR;
228 return DEVIATE_ADD_SUBSTATEMENT_VALIDATOR;
230 return DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR;
232 return DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR;
234 throw new IllegalStateException(String.format(
235 "Substatement validator for deviate %s has not been defined.", deviateKind));
239 private static boolean isDeviationSupported(
240 final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx,
241 final SchemaNodeIdentifier deviationTarget) {
242 final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules = deviateStmtCtx.getFromNamespace(
243 ModulesDeviatedByModules.class, Empty.value());
244 if (modulesDeviatedByModules == null) {
248 final QNameModule currentModule = deviateStmtCtx.getFromNamespace(ModuleCtxToModuleQName.class,
249 deviateStmtCtx.getRoot());
250 final QNameModule targetModule = Iterables.getLast(deviationTarget.getNodeIdentifiers()).getModule();
252 final Set<QNameModule> deviationModulesSupportedByTargetModule = modulesDeviatedByModules.get(targetModule);
253 if (deviationModulesSupportedByTargetModule != null) {
254 return deviationModulesSupportedByTargetModule.contains(currentModule);
260 private static void performDeviateAdd(final StmtContext<?, ?, ?> deviateStmtCtx,
261 final Mutable<?, ?, ?> targetCtx) {
262 for (StmtContext<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
263 validateDeviationTarget(originalStmtCtx, targetCtx);
264 addStatement(originalStmtCtx, targetCtx);
268 private static void addStatement(final StmtContext<?, ?, ?> stmtCtxToBeAdded, final Mutable<?, ?, ?> targetCtx) {
269 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeAdded)) {
270 final StatementDefinition stmtToBeAdded = stmtCtxToBeAdded.publicDefinition();
271 if (SINGLETON_STATEMENTS.contains(stmtToBeAdded) || YangStmtMapping.DEFAULT.equals(stmtToBeAdded)
272 && YangStmtMapping.LEAF.equals(targetCtx.publicDefinition())) {
273 for (StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.allSubstatements()) {
274 InferenceException.throwIf(stmtToBeAdded.equals(targetCtxSubstatement.publicDefinition()),
276 "Deviation cannot add substatement %s to target node %s because it is already defined "
277 + "in target and can appear only once.",
278 stmtToBeAdded.getStatementName(), targetCtx.argument());
283 copyStatement(stmtCtxToBeAdded, targetCtx);
286 private static void performDeviateReplace(final StmtContext<?, ?, ?> deviateStmtCtx,
287 final Mutable<?, ?, ?> targetCtx) {
288 for (StmtContext<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
289 validateDeviationTarget(originalStmtCtx, targetCtx);
290 replaceStatement(originalStmtCtx, targetCtx);
294 private static void replaceStatement(final StmtContext<?, ?, ?> stmtCtxToBeReplaced,
295 final Mutable<?, ?, ?> targetCtx) {
296 final StatementDefinition stmtToBeReplaced = stmtCtxToBeReplaced.publicDefinition();
298 if (YangStmtMapping.DEFAULT.equals(stmtToBeReplaced)
299 && YangStmtMapping.LEAF_LIST.equals(targetCtx.publicDefinition())) {
300 LOG.error("Deviation cannot replace substatement {} in target leaf-list {} because a leaf-list can "
301 + "have multiple default statements. At line: {}", stmtToBeReplaced.getStatementName(),
302 targetCtx.argument(), stmtCtxToBeReplaced.sourceReference());
306 for (StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.effectiveSubstatements()) {
307 if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
308 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeReplaced);
309 copyStatement(stmtCtxToBeReplaced, targetCtx);
314 for (Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
315 if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
316 targetCtxSubstatement.setUnsupported();
317 copyStatement(stmtCtxToBeReplaced, targetCtx);
322 // This is a special case when deviate replace of a config/mandatory/max/min-elements substatement targets
323 // a node which does not contain an explicitly declared config/mandatory/max/min-elements.
324 // However, according to RFC6020/RFC7950, these properties are always implicitly present.
325 if (IMPLICIT_STATEMENTS.contains(stmtToBeReplaced)) {
326 addStatement(stmtCtxToBeReplaced, targetCtx);
330 throw new InferenceException(stmtCtxToBeReplaced,
331 "Deviation cannot replace substatement %s in target node %s because it does not exist in target node.",
332 stmtToBeReplaced.getStatementName(), targetCtx.argument());
335 private static void performDeviateDelete(final StmtContext<?, ?, ?> deviateStmtCtx,
336 final Mutable<?, ?, ?> targetCtx) {
337 for (StmtContext<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
338 validateDeviationTarget(originalStmtCtx, targetCtx);
339 deleteStatement(originalStmtCtx, targetCtx);
343 private static void deleteStatement(final StmtContext<?, ?, ?> stmtCtxToBeDeleted,
344 final Mutable<?, ?, ?> targetCtx) {
345 final StatementDefinition stmtToBeDeleted = stmtCtxToBeDeleted.publicDefinition();
346 final String stmtArgument = stmtCtxToBeDeleted.rawArgument();
348 for (Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableEffectiveSubstatements()) {
349 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
350 targetCtxSubstatement.rawArgument())) {
351 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeDeleted, stmtArgument);
356 for (Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
357 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
358 targetCtxSubstatement.rawArgument())) {
359 targetCtxSubstatement.setUnsupported();
364 LOG.error("Deviation cannot delete substatement {} with argument '{}' in target node {} because it does "
365 + "not exist in the target node. At line: {}", stmtToBeDeleted.getStatementName(), stmtArgument,
366 targetCtx.argument(), stmtCtxToBeDeleted.sourceReference());
369 private static void copyStatement(final StmtContext<?, ?, ?> stmtCtxToBeCopied, final Mutable<?, ?, ?> targetCtx) {
370 // we need to make a copy of the statement context only if it is an unknown statement, otherwise
371 // we can reuse the original statement context
372 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeCopied)) {
373 // FIXME: I think this should be handled by the corresponding support's copy policy
374 targetCtx.addEffectiveSubstatement(stmtCtxToBeCopied.replicaAsChildOf(targetCtx));
376 targetCtx.addEffectiveSubstatement(targetCtx.childCopyOf(stmtCtxToBeCopied, CopyType.ORIGINAL));
380 private static boolean statementsAreEqual(final StatementDefinition firstStmtDef, final String firstStmtArg,
381 final StatementDefinition secondStmtDef, final String secondStmtArg) {
382 return firstStmtDef.equals(secondStmtDef) && Objects.equals(firstStmtArg, secondStmtArg);
385 private static void validateDeviationTarget(final StmtContext<?, ?, ?> deviateSubStmtCtx,
386 final StmtContext<?, ?, ?> targetCtx) {
387 InferenceException.throwIf(!isSupportedDeviationTarget(deviateSubStmtCtx, targetCtx,
388 targetCtx.yangVersion()), deviateSubStmtCtx,
389 "%s is not a valid deviation target for substatement %s.", targetCtx.argument(),
390 deviateSubStmtCtx.publicDefinition().getStatementName());
393 private static boolean isSupportedDeviationTarget(final StmtContext<?, ?, ?> deviateSubstatementCtx,
394 final StmtContext<?, ?, ?> deviateTargetCtx, final YangVersion yangVersion) {
395 Set<StatementDefinition> supportedDeviationTargets =
396 YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(yangVersion,
397 deviateSubstatementCtx.publicDefinition());
399 if (supportedDeviationTargets == null) {
400 supportedDeviationTargets = YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(YangVersion.VERSION_1,
401 deviateSubstatementCtx.publicDefinition());
404 // if supportedDeviationTargets is null, it means that the deviate substatement is an unknown statement
405 return supportedDeviationTargets == null || supportedDeviationTargets.contains(
406 deviateTargetCtx.publicDefinition());