a302e56d7f164e213ca335a596a9fa8de36935e9
[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.utils.mapping.RestconfMappingNodeUtil;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.monitoring.rev170126.RestconfState;
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.EffectiveModelContextListener;
39 import org.opendaylight.yangtools.yang.model.api.Module;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * Implementation of {@link SchemaContextHandler}.
45  */
46 // FIXME: this really is a service which is maintaining ietf-yang-library contents inside the datastore. It really
47 //        should live in MD-SAL and be a dynamic store fragment. As a first step we should be turning this into a
48 //        completely standalone application.
49 @Singleton
50 public class SchemaContextHandler implements EffectiveModelContextListener, AutoCloseable {
51     private static final Logger LOG = LoggerFactory.getLogger(SchemaContextHandler.class);
52
53     private final AtomicInteger moduleSetId = new AtomicInteger(0);
54
55     private final TransactionChainHandler transactionChainHandler;
56     private final DOMSchemaService domSchemaService;
57     private ListenerRegistration<?> listenerRegistration;
58
59     private volatile EffectiveModelContext schemaContext;
60
61     /**
62      * Constructor.
63      *
64      * @param transactionChainHandler Transaction chain handler
65      */
66     @Inject
67     public SchemaContextHandler(final TransactionChainHandler transactionChainHandler,
68             final @Reference DOMSchemaService domSchemaService) {
69         this.transactionChainHandler = transactionChainHandler;
70         this.domSchemaService = domSchemaService;
71     }
72
73     @PostConstruct
74     public void init() {
75         listenerRegistration = domSchemaService.registerSchemaContextListener(this);
76     }
77
78     @Override
79     @PreDestroy
80     public void close() {
81         if (listenerRegistration != null) {
82             listenerRegistration.close();
83         }
84     }
85
86     @Override
87     public void onModelContextUpdated(final EffectiveModelContext context) {
88         schemaContext = requireNonNull(context);
89
90         if (context.findModule(IetfYangLibrary.MODULE_QNAME).isPresent()) {
91             putData(RestconfMappingNodeUtil.mapModulesByIetfYangLibraryYang(context.getModules(), context,
92                 String.valueOf(this.moduleSetId.incrementAndGet())));
93         }
94
95         final Module monitoringModule = schemaContext.findModule(RestconfState.QNAME.getModule()).orElse(null);
96         if (monitoringModule != null) {
97             putData(RestconfMappingNodeUtil.mapCapabilites(monitoringModule));
98         }
99     }
100
101     public EffectiveModelContext get() {
102         return schemaContext;
103     }
104
105     private void putData(
106             final NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> normNode) {
107         final DOMTransactionChain transactionChain = this.transactionChainHandler.get();
108         final DOMDataTreeWriteTransaction wTx = transactionChain.newWriteOnlyTransaction();
109         wTx.put(LogicalDatastoreType.OPERATIONAL,
110                 YangInstanceIdentifier.create(NodeIdentifier.create(normNode.getNodeType())), normNode);
111         try {
112             wTx.commit().get();
113         } catch (InterruptedException e) {
114             throw new RestconfDocumentedException("Problem occurred while putting data to DS.", e);
115         } catch (ExecutionException e) {
116             final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
117                 TransactionCommitFailedException.class);
118             if (failure.getCause() instanceof ConflictingModificationAppliedException) {
119                 /*
120                  * Ignore error when another cluster node is already putting the same data to DS.
121                  * We expect that cluster is homogeneous and that node was going to write the same data
122                  * (that means no retry is needed). Transaction chain reset must be invoked to be able
123                  * to continue writing data with another transaction after failed transaction.
124                  * This is workaround for bug https://bugs.opendaylight.org/show_bug.cgi?id=7728
125                  */
126                 LOG.warn("Ignoring that another cluster node is already putting the same data to DS.", e);
127             } else {
128                 throw new RestconfDocumentedException("Problem occurred while putting data to DS.", failure);
129             }
130         } finally {
131             transactionChain.close();
132         }
133     }
134 }