Reorganize transactionChainHandler usage.
[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.Module;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * Implementation of {@link SchemaContextHandler}.
45  */
46 @Singleton
47 @SuppressWarnings("checkstyle:FinalClass")
48 public class SchemaContextHandler implements SchemaContextListenerHandler, AutoCloseable {
49
50     private static final Logger LOG = LoggerFactory.getLogger(SchemaContextHandler.class);
51
52     private final AtomicInteger moduleSetId = new AtomicInteger(0);
53
54     private final TransactionChainHandler transactionChainHandler;
55     private final DOMSchemaService domSchemaService;
56     private ListenerRegistration<SchemaContextListener> listenerRegistration;
57
58     private volatile SchemaContext schemaContext;
59
60     /**
61      * Constructor.
62      *
63      * @param transactionChainHandler Transaction chain handler
64      */
65     @Inject
66     public SchemaContextHandler(final TransactionChainHandler transactionChainHandler,
67             final @Reference DOMSchemaService domSchemaService) {
68         this.transactionChainHandler = transactionChainHandler;
69         this.domSchemaService = domSchemaService;
70     }
71
72     @Deprecated
73     public static SchemaContextHandler newInstance(final TransactionChainHandler transactionChainHandler,
74             final DOMSchemaService domSchemaService) {
75         return new SchemaContextHandler(transactionChainHandler, domSchemaService);
76     }
77
78     @PostConstruct
79     public void init() {
80         listenerRegistration = domSchemaService.registerSchemaContextListener(this);
81     }
82
83     @Override
84     @PreDestroy
85     public void close() {
86         if (listenerRegistration != null) {
87             listenerRegistration.close();
88         }
89     }
90
91     @Override
92     @SuppressWarnings("checkstyle:hiddenField")
93     public void onGlobalContextUpdated(final SchemaContext context) {
94         schemaContext = requireNonNull(context);
95
96         final Module ietfYangLibraryModule =
97                 context.findModule(IetfYangLibrary.MODULE_QNAME).orElse(null);
98         if (ietfYangLibraryModule != null) {
99             NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> normNode =
100                     RestconfMappingNodeUtil.mapModulesByIetfYangLibraryYang(context.getModules(), ietfYangLibraryModule,
101                             context, String.valueOf(this.moduleSetId.incrementAndGet()));
102             putData(normNode);
103         }
104
105         final Module monitoringModule =
106                 schemaContext.findModule(MonitoringModule.MODULE_QNAME).orElse(null);
107         if (monitoringModule != null) {
108             NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> normNode =
109                     RestconfMappingNodeUtil.mapCapabilites(monitoringModule);
110             putData(normNode);
111         }
112     }
113
114     @Override
115     public SchemaContext get() {
116         return schemaContext;
117     }
118
119     private void putData(
120             final NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> normNode) {
121         final DOMTransactionChain transactionChain = this.transactionChainHandler.get();
122         final DOMDataTreeWriteTransaction wTx = transactionChain.newWriteOnlyTransaction();
123         wTx.put(LogicalDatastoreType.OPERATIONAL,
124                 YangInstanceIdentifier.create(NodeIdentifier.create(normNode.getNodeType())), normNode);
125         try {
126             wTx.commit().get();
127         } catch (InterruptedException e) {
128             throw new RestconfDocumentedException("Problem occurred while putting data to DS.", e);
129         } catch (ExecutionException e) {
130             final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
131                 TransactionCommitFailedException.class);
132             if (failure.getCause() instanceof ConflictingModificationAppliedException) {
133                 /*
134                  * Ignore error when another cluster node is already putting the same data to DS.
135                  * We expect that cluster is homogeneous and that node was going to write the same data
136                  * (that means no retry is needed). Transaction chain reset must be invoked to be able
137                  * to continue writing data with another transaction after failed transaction.
138                  * This is workaround for bug https://bugs.opendaylight.org/show_bug.cgi?id=7728
139                  */
140                 LOG.warn("Ignoring that another cluster node is already putting the same data to DS.", e);
141             } else {
142                 throw new RestconfDocumentedException("Problem occurred while putting data to DS.", failure);
143             }
144         } finally {
145             transactionChain.close();
146         }
147     }
148 }