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