f9d85c5b1b8dcdacad4892f25c6a0fa0429987ab
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / stmt / deviate / AbstractDeviateStatementSupport.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies, s.r.o. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.parser.rfc7950.stmt.deviate;
9
10 import com.google.common.collect.ImmutableMap;
11 import com.google.common.collect.ImmutableSet;
12 import com.google.common.collect.Iterables;
13 import com.google.common.collect.Maps;
14 import com.google.common.collect.SetMultimap;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.util.Arrays;
17 import java.util.Collection;
18 import java.util.Objects;
19 import java.util.Set;
20 import org.opendaylight.yangtools.yang.common.QNameModule;
21 import org.opendaylight.yangtools.yang.common.YangVersion;
22 import org.opendaylight.yangtools.yang.model.api.DeviateKind;
23 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
24 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
25 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
26 import org.opendaylight.yangtools.yang.model.api.stmt.DeviateEffectiveStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.DeviateStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
29 import org.opendaylight.yangtools.yang.parser.rfc7950.namespace.ChildSchemaNodeNamespace;
30 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
43 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
44 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
45 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
46 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
47 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 abstract class AbstractDeviateStatementSupport
52         extends AbstractStatementSupport<DeviateKind, DeviateStatement, DeviateEffectiveStatement> {
53     private static final Logger LOG = LoggerFactory.getLogger(AbstractDeviateStatementSupport.class);
54
55     private static final SubstatementValidator DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR =
56             SubstatementValidator.builder(YangStmtMapping.DEVIATE).build();
57
58     private static final SubstatementValidator DEVIATE_ADD_SUBSTATEMENT_VALIDATOR =
59             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
60                 .addOptional(YangStmtMapping.CONFIG)
61                 .addOptional(YangStmtMapping.DEFAULT)
62                 .addOptional(YangStmtMapping.MANDATORY)
63                 .addOptional(YangStmtMapping.MAX_ELEMENTS)
64                 .addOptional(YangStmtMapping.MIN_ELEMENTS)
65                 .addAny(YangStmtMapping.MUST)
66                 .addAny(YangStmtMapping.UNIQUE)
67                 .addOptional(YangStmtMapping.UNITS)
68                 .build();
69
70     private static final SubstatementValidator DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR =
71             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
72                 .addOptional(YangStmtMapping.CONFIG)
73                 .addOptional(YangStmtMapping.DEFAULT)
74                 .addOptional(YangStmtMapping.MANDATORY)
75                 .addOptional(YangStmtMapping.MAX_ELEMENTS)
76                 .addOptional(YangStmtMapping.MIN_ELEMENTS)
77                 .addOptional(YangStmtMapping.TYPE)
78                 .addOptional(YangStmtMapping.UNITS)
79                 .build();
80
81     private static final SubstatementValidator DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR =
82             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
83                 .addOptional(YangStmtMapping.DEFAULT)
84                 .addAny(YangStmtMapping.MUST)
85                 .addAny(YangStmtMapping.UNIQUE)
86                 .addOptional(YangStmtMapping.UNITS)
87                 .build();
88
89     private static final ImmutableMap<String, DeviateKind> KEYWORD_TO_DEVIATE_MAP =
90             Maps.uniqueIndex(Arrays.asList(DeviateKind.values()), DeviateKind::getKeyword);
91
92     private static final ImmutableSet<YangStmtMapping> SINGLETON_STATEMENTS = ImmutableSet.of(
93             YangStmtMapping.UNITS, YangStmtMapping.CONFIG, YangStmtMapping.MANDATORY,
94             YangStmtMapping.MIN_ELEMENTS, YangStmtMapping.MAX_ELEMENTS);
95
96     private static final ImmutableSet<YangStmtMapping> IMPLICIT_STATEMENTS = ImmutableSet.of(YangStmtMapping.CONFIG,
97             YangStmtMapping.MANDATORY, YangStmtMapping.MAX_ELEMENTS, YangStmtMapping.MIN_ELEMENTS);
98
99     AbstractDeviateStatementSupport() {
100         super(YangStmtMapping.DEVIATE);
101     }
102
103     @Override
104     public final DeviateKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
105         return SourceException.throwIfNull(KEYWORD_TO_DEVIATE_MAP.get(value),
106             ctx.getStatementSourceReference(), "String '%s' is not valid deviate argument", value);
107     }
108
109     @Override
110     public final DeviateStatement createDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx) {
111         return new DeviateStatementImpl(ctx);
112     }
113
114     @Override
115     public final DeviateEffectiveStatement createEffective(
116             final StmtContext<DeviateKind, DeviateStatement, DeviateEffectiveStatement> ctx) {
117         return new DeviateEffectiveStatementImpl(ctx);
118     }
119
120     @Override
121     public final void onFullDefinitionDeclared(
122             final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx) {
123         final DeviateKind deviateKind = deviateStmtCtx.getStatementArgument();
124         getSubstatementValidatorForDeviate(deviateKind).validate(deviateStmtCtx);
125
126         final SchemaNodeIdentifier deviationTarget =
127                 (SchemaNodeIdentifier) deviateStmtCtx.coerceParentContext().getStatementArgument();
128
129         if (!isDeviationSupported(deviateStmtCtx, deviationTarget)) {
130             return;
131         }
132
133         final ModelActionBuilder deviateAction = deviateStmtCtx.newInferenceAction(
134                 ModelProcessingPhase.EFFECTIVE_MODEL);
135
136         final Prerequisite<StmtContext<DeviateKind, DeviateStatement,
137             DeviateEffectiveStatement>> sourceCtxPrerequisite =
138                 deviateAction.requiresCtx(deviateStmtCtx, ModelProcessingPhase.EFFECTIVE_MODEL);
139
140         final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> targetCtxPrerequisite =
141                 deviateAction.mutatesEffectiveCtxPath(deviateStmtCtx.getRoot(),
142                     ChildSchemaNodeNamespace.class, deviationTarget.getNodeIdentifiers());
143
144         deviateAction.apply(new InferenceAction() {
145             @Override
146             public void apply(final InferenceContext ctx) {
147                 // FIXME once BUG-7760 gets fixed, there will be no need for these dirty casts
148                 final StatementContextBase<?, ?, ?> sourceNodeStmtCtx =
149                         (StatementContextBase<?, ?, ?>) sourceCtxPrerequisite.resolve(ctx);
150                 final StatementContextBase<?, ?, ?> targetNodeStmtCtx =
151                         (StatementContextBase<?, ?, ?>) targetCtxPrerequisite.resolve(ctx);
152
153                 switch (deviateKind) {
154                     case NOT_SUPPORTED:
155                         targetNodeStmtCtx.setIsSupportedToBuildEffective(false);
156                         break;
157                     case ADD:
158                         performDeviateAdd(sourceNodeStmtCtx, targetNodeStmtCtx);
159                         break;
160                     case REPLACE:
161                         performDeviateReplace(sourceNodeStmtCtx, targetNodeStmtCtx);
162                         break;
163                     case DELETE:
164                         performDeviateDelete(sourceNodeStmtCtx, targetNodeStmtCtx);
165                         break;
166                     default:
167                         throw new IllegalStateException("Unsupported deviate " + deviateKind);
168                 }
169             }
170
171             @Override
172             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
173                 throw new InferenceException(deviateStmtCtx.coerceParentContext().getStatementSourceReference(),
174                     "Deviation target '%s' not found.", deviationTarget);
175             }
176         });
177     }
178
179     @Override
180     public String internArgument(final String rawArgument) {
181         if ("add".equals(rawArgument)) {
182             return "add";
183         } else if ("delete".equals(rawArgument)) {
184             return "delete";
185         } else if ("replace".equals(rawArgument)) {
186             return "replace";
187         } else if ("not-supported".equals(rawArgument)) {
188             return "not-supported";
189         } else {
190             return rawArgument;
191         }
192     }
193
194     @Override
195     protected final SubstatementValidator getSubstatementValidator() {
196         return null;
197     }
198
199     protected SubstatementValidator getSubstatementValidatorForDeviate(final DeviateKind deviateKind) {
200         switch (deviateKind) {
201             case NOT_SUPPORTED:
202                 return DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR;
203             case ADD:
204                 return DEVIATE_ADD_SUBSTATEMENT_VALIDATOR;
205             case REPLACE:
206                 return DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR;
207             case DELETE:
208                 return DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR;
209             default:
210                 throw new IllegalStateException(String.format(
211                         "Substatement validator for deviate %s has not been defined.", deviateKind));
212         }
213     }
214
215     private static boolean isDeviationSupported(
216             final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx,
217             final SchemaNodeIdentifier deviationTarget) {
218         final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules = deviateStmtCtx.getFromNamespace(
219                 ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES);
220         if (modulesDeviatedByModules == null) {
221             return true;
222         }
223
224         final QNameModule currentModule = deviateStmtCtx.getFromNamespace(ModuleCtxToModuleQName.class,
225                 deviateStmtCtx.getRoot());
226         final QNameModule targetModule = Iterables.getLast(deviationTarget.getNodeIdentifiers()).getModule();
227
228         final Set<QNameModule> deviationModulesSupportedByTargetModule = modulesDeviatedByModules.get(targetModule);
229         if (deviationModulesSupportedByTargetModule != null) {
230             return deviationModulesSupportedByTargetModule.contains(currentModule);
231         }
232
233         return false;
234     }
235
236     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
237             justification = "https://github.com/spotbugs/spotbugs/issues/811")
238     private static void performDeviateAdd(final StatementContextBase<?, ?, ?> deviateStmtCtx,
239             final StatementContextBase<?, ?, ?> targetCtx) {
240         for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
241             validateDeviationTarget(originalStmtCtx, targetCtx);
242             addStatement(originalStmtCtx, targetCtx);
243         }
244     }
245
246     private static void addStatement(final Mutable<?, ?, ?> stmtCtxToBeAdded,
247             final StatementContextBase<?, ?, ?> targetCtx) {
248         if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeAdded)) {
249             final StatementDefinition stmtToBeAdded = stmtCtxToBeAdded.getPublicDefinition();
250             if (SINGLETON_STATEMENTS.contains(stmtToBeAdded) || YangStmtMapping.DEFAULT.equals(stmtToBeAdded)
251                     && YangStmtMapping.LEAF.equals(targetCtx.getPublicDefinition())) {
252                 for (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.allSubstatements()) {
253                     InferenceException.throwIf(stmtToBeAdded.equals(targetCtxSubstatement.getPublicDefinition()),
254                         stmtCtxToBeAdded.getStatementSourceReference(),
255                         "Deviation cannot add substatement %s to target node %s because it is already defined "
256                         + "in target and can appear only once.",
257                         stmtToBeAdded.getStatementName(), targetCtx.getStatementArgument());
258                 }
259             }
260         }
261
262         copyStatement(stmtCtxToBeAdded, targetCtx);
263     }
264
265     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
266             justification = "https://github.com/spotbugs/spotbugs/issues/811")
267     private static void performDeviateReplace(final StatementContextBase<?, ?, ?> deviateStmtCtx,
268             final StatementContextBase<?, ?, ?> targetCtx) {
269         for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
270             validateDeviationTarget(originalStmtCtx, targetCtx);
271             replaceStatement(originalStmtCtx, targetCtx);
272         }
273     }
274
275     private static void replaceStatement(final Mutable<?, ?, ?> stmtCtxToBeReplaced,
276             final StatementContextBase<?, ?, ?> targetCtx) {
277         final StatementDefinition stmtToBeReplaced = stmtCtxToBeReplaced.getPublicDefinition();
278
279         if (YangStmtMapping.DEFAULT.equals(stmtToBeReplaced)
280                 && YangStmtMapping.LEAF_LIST.equals(targetCtx.getPublicDefinition())) {
281             LOG.error("Deviation cannot replace substatement {} in target leaf-list {} because a leaf-list can "
282                     + "have multiple default statements. At line: {}", stmtToBeReplaced.getStatementName(),
283                     targetCtx.getStatementArgument(), stmtCtxToBeReplaced.getStatementSourceReference());
284             return;
285         }
286
287         for (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.effectiveSubstatements()) {
288             if (stmtToBeReplaced.equals(targetCtxSubstatement.getPublicDefinition())) {
289                 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeReplaced);
290                 copyStatement(stmtCtxToBeReplaced, targetCtx);
291                 return;
292             }
293         }
294
295         for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
296             if (stmtToBeReplaced.equals(targetCtxSubstatement.getPublicDefinition())) {
297                 targetCtxSubstatement.setIsSupportedToBuildEffective(false);
298                 copyStatement(stmtCtxToBeReplaced, targetCtx);
299                 return;
300             }
301         }
302
303         // This is a special case when deviate replace of a config/mandatory/max/min-elements substatement targets
304         // a node which does not contain an explicitly declared config/mandatory/max/min-elements.
305         // However, according to RFC6020/RFC7950, these properties are always implicitly present.
306         if (IMPLICIT_STATEMENTS.contains(stmtToBeReplaced)) {
307             addStatement(stmtCtxToBeReplaced, targetCtx);
308             return;
309         }
310
311         throw new InferenceException(stmtCtxToBeReplaced.getStatementSourceReference(), "Deviation cannot replace "
312                 + "substatement %s in target node %s because it does not exist in target node.",
313                 stmtToBeReplaced.getStatementName(), targetCtx.getStatementArgument());
314     }
315
316     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
317             justification = "https://github.com/spotbugs/spotbugs/issues/811")
318     private static void performDeviateDelete(final StatementContextBase<?, ?, ?> deviateStmtCtx,
319             final StatementContextBase<?, ?, ?> targetCtx) {
320         for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
321             validateDeviationTarget(originalStmtCtx, targetCtx);
322             deleteStatement(originalStmtCtx, targetCtx);
323         }
324     }
325
326     private static void deleteStatement(final StmtContext<?, ?, ?> stmtCtxToBeDeleted,
327             final StatementContextBase<?, ?, ?> targetCtx) {
328         final StatementDefinition stmtToBeDeleted = stmtCtxToBeDeleted.getPublicDefinition();
329         final String stmtArgument = stmtCtxToBeDeleted.rawStatementArgument();
330
331         for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableEffectiveSubstatements()) {
332             if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.getPublicDefinition(),
333                     targetCtxSubstatement.rawStatementArgument())) {
334                 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeDeleted, stmtArgument);
335                 return;
336             }
337         }
338
339         for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
340             if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.getPublicDefinition(),
341                     targetCtxSubstatement.rawStatementArgument())) {
342                 targetCtxSubstatement.setIsSupportedToBuildEffective(false);
343                 return;
344             }
345         }
346
347         LOG.error("Deviation cannot delete substatement {} with argument '{}' in target node {} because it does "
348                 + "not exist in the target node. At line: {}", stmtToBeDeleted.getStatementName(), stmtArgument,
349                 targetCtx.getStatementArgument(), stmtCtxToBeDeleted.getStatementSourceReference());
350     }
351
352     private static void copyStatement(final Mutable<?, ?, ?> stmtCtxToBeCopied,
353             final StatementContextBase<?, ?, ?> targetCtx) {
354         // we need to make a copy of the statement context only if it is an unknown statement, otherwise
355         // we can reuse the original statement context
356         if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeCopied)) {
357             targetCtx.addEffectiveSubstatement(stmtCtxToBeCopied);
358         } else {
359             targetCtx.addEffectiveSubstatement(targetCtx.childCopyOf(stmtCtxToBeCopied, CopyType.ORIGINAL));
360         }
361     }
362
363     private static boolean statementsAreEqual(final StatementDefinition firstStmtDef, final String firstStmtArg,
364             final StatementDefinition secondStmtDef, final String secondStmtArg) {
365         return firstStmtDef.equals(secondStmtDef) && Objects.equals(firstStmtArg, secondStmtArg);
366     }
367
368     private static void validateDeviationTarget(final StmtContext<?, ?, ?> deviateSubStmtCtx,
369             final StmtContext<?, ?, ?> targetCtx) {
370         InferenceException.throwIf(!isSupportedDeviationTarget(deviateSubStmtCtx, targetCtx,
371                 targetCtx.getRootVersion()), deviateSubStmtCtx.getStatementSourceReference(),
372                 "%s is not a valid deviation target for substatement %s.",
373                 targetCtx.getStatementArgument(), deviateSubStmtCtx.getPublicDefinition().getStatementName());
374     }
375
376     private static boolean isSupportedDeviationTarget(final StmtContext<?, ?, ?> deviateSubstatementCtx,
377             final StmtContext<?, ?, ?> deviateTargetCtx, final YangVersion yangVersion) {
378         Set<StatementDefinition> supportedDeviationTargets =
379                 YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(deviateTargetCtx.getRootVersion(),
380                         deviateSubstatementCtx.getPublicDefinition());
381
382         if (supportedDeviationTargets == null) {
383             supportedDeviationTargets = YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(YangVersion.VERSION_1,
384                     deviateSubstatementCtx.getPublicDefinition());
385         }
386
387         // if supportedDeviationTargets is null, it means that the deviate substatement is an unknown statement
388         return supportedDeviationTargets == null || supportedDeviationTargets.contains(
389                 deviateTargetCtx.getPublicDefinition());
390     }
391 }