c40bf84c5741673fd5600d3116f48f36e08ccdf9
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / handlers / SchemaContextHandler.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. 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.restconf.nb.rfc8040.handlers;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.Throwables;
13 import java.util.Collection;
14 import java.util.concurrent.ExecutionException;
15 import java.util.concurrent.atomic.AtomicInteger;
16 import javax.annotation.PostConstruct;
17 import javax.annotation.PreDestroy;
18 import javax.inject.Inject;
19 import javax.inject.Singleton;
20 import org.apache.aries.blueprint.annotation.service.Reference;
21 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
22 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
23 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
24 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
25 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
26 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
27 import org.opendaylight.restconf.nb.rfc8040.Rfc8040.IetfYangLibrary;
28 import org.opendaylight.restconf.nb.rfc8040.Rfc8040.MonitoringModule;
29 import org.opendaylight.restconf.nb.rfc8040.utils.mapping.RestconfMappingNodeUtil;
30 import org.opendaylight.yangtools.concepts.ListenerRegistration;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
37 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
38 import org.opendaylight.yangtools.yang.model.api.Module;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Implementation of {@link SchemaContextHandler}.
44  */
45 @Singleton
46 @SuppressWarnings("checkstyle:FinalClass")
47 public class SchemaContextHandler implements SchemaContextListenerHandler, AutoCloseable {
48
49     private static final Logger LOG = LoggerFactory.getLogger(SchemaContextHandler.class);
50
51     private final AtomicInteger moduleSetId = new AtomicInteger(0);
52
53     private final TransactionChainHandler transactionChainHandler;
54     private final DOMSchemaService domSchemaService;
55     private ListenerRegistration<?> listenerRegistration;
56
57     private volatile EffectiveModelContext schemaContext;
58
59     /**
60      * Constructor.
61      *
62      * @param transactionChainHandler Transaction chain handler
63      */
64     @Inject
65     public SchemaContextHandler(final TransactionChainHandler transactionChainHandler,
66             final @Reference DOMSchemaService domSchemaService) {
67         this.transactionChainHandler = transactionChainHandler;
68         this.domSchemaService = domSchemaService;
69     }
70
71     @Deprecated
72     public static SchemaContextHandler newInstance(final TransactionChainHandler transactionChainHandler,
73             final DOMSchemaService domSchemaService) {
74         return new SchemaContextHandler(transactionChainHandler, domSchemaService);
75     }
76
77     @PostConstruct
78     public void init() {
79         listenerRegistration = domSchemaService.registerSchemaContextListener(this);
80     }
81
82     @Override
83     @PreDestroy
84     public void close() {
85         if (listenerRegistration != null) {
86             listenerRegistration.close();
87         }
88     }
89
90     @Override
91     @SuppressWarnings("checkstyle:hiddenField")
92     public void onModelContextUpdated(final EffectiveModelContext context) {
93         schemaContext = requireNonNull(context);
94
95         final Module ietfYangLibraryModule =
96                 context.findModule(IetfYangLibrary.MODULE_QNAME).orElse(null);
97         if (ietfYangLibraryModule != null) {
98             NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> normNode =
99                     RestconfMappingNodeUtil.mapModulesByIetfYangLibraryYang(context.getModules(), ietfYangLibraryModule,
100                             context, String.valueOf(this.moduleSetId.incrementAndGet()));
101             putData(normNode);
102         }
103
104         final Module monitoringModule =
105                 schemaContext.findModule(MonitoringModule.MODULE_QNAME).orElse(null);
106         if (monitoringModule != null) {
107             NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> normNode =
108                     RestconfMappingNodeUtil.mapCapabilites(monitoringModule);
109             putData(normNode);
110         }
111     }
112
113     @Override
114     public EffectiveModelContext get() {
115         return schemaContext;
116     }
117
118     private void putData(
119             final NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> normNode) {
120         final DOMTransactionChain transactionChain = this.transactionChainHandler.get();
121         final DOMDataTreeWriteTransaction wTx = transactionChain.newWriteOnlyTransaction();
122         wTx.put(LogicalDatastoreType.OPERATIONAL,
123                 YangInstanceIdentifier.create(NodeIdentifier.create(normNode.getNodeType())), normNode);
124         try {
125             wTx.commit().get();
126         } catch (InterruptedException e) {
127             throw new RestconfDocumentedException("Problem occurred while putting data to DS.", e);
128         } catch (ExecutionException e) {
129             final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
130                 TransactionCommitFailedException.class);
131             if (failure.getCause() instanceof ConflictingModificationAppliedException) {
132                 /*
133                  * Ignore error when another cluster node is already putting the same data to DS.
134                  * We expect that cluster is homogeneous and that node was going to write the same data
135                  * (that means no retry is needed). Transaction chain reset must be invoked to be able
136                  * to continue writing data with another transaction after failed transaction.
137                  * This is workaround for bug https://bugs.opendaylight.org/show_bug.cgi?id=7728
138                  */
139                 LOG.warn("Ignoring that another cluster node is already putting the same data to DS.", e);
140             } else {
141                 throw new RestconfDocumentedException("Problem occurred while putting data to DS.", failure);
142             }
143         } finally {
144             transactionChain.close();
145         }
146     }
147 }