fda289e2ba9730afd70c275ee8cc5fd2b6ff1d97
[hc2vpp.git] /
1 /*
2  * Copyright (c) 2016 Cisco and/or its affiliates.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package io.fd.honeycomb.v3po.translate.util.write;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20 import static com.google.common.base.Preconditions.checkNotNull;
21
22 import com.google.common.base.Function;
23 import com.google.common.collect.Collections2;
24 import com.google.common.collect.Iterables;
25 import com.google.common.collect.Lists;
26 import com.google.common.collect.Sets;
27 import io.fd.honeycomb.v3po.translate.TranslationException;
28 import io.fd.honeycomb.v3po.translate.util.RWUtils;
29 import io.fd.honeycomb.v3po.translate.write.WriteContext;
30 import io.fd.honeycomb.v3po.translate.write.Writer;
31 import io.fd.honeycomb.v3po.translate.write.WriterRegistry;
32 import java.util.LinkedList;
33 import java.util.List;
34 import java.util.Map;
35 import javax.annotation.Nonnull;
36 import javax.annotation.Nullable;
37 import org.opendaylight.yangtools.yang.binding.DataObject;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Simple writer registry able to perform and aggregated read (ROOT write) on top of all provided writers. Also able to
44  * delegate a specific read to one of the delegate writers.
45  *
46  * This could serve as a utility to hold & hide all available writers in upper layers.
47  */
48 public final class DelegatingWriterRegistry implements WriterRegistry {
49
50     private static final Logger LOG = LoggerFactory.getLogger(DelegatingWriterRegistry.class);
51
52     private static final Function<InstanceIdentifier<?>, Class<? extends DataObject>> ID_TO_CLASS =
53             new Function<InstanceIdentifier<?>, Class<? extends DataObject>>() {
54                 @Override
55                 public Class<? extends DataObject> apply(final InstanceIdentifier<?> input) {
56                     return input.getTargetType();
57                 }
58             };
59
60     private final Map<Class<? extends DataObject>, Writer<? extends DataObject>> rootWriters;
61
62     /**
63      * Create new {@link DelegatingWriterRegistry}
64      *
65      * @param rootWriters List of delegate writers
66      */
67     public DelegatingWriterRegistry(@Nonnull final List<Writer<? extends DataObject>> rootWriters) {
68         this.rootWriters = RWUtils.uniqueLinkedIndex(checkNotNull(rootWriters), RWUtils.MANAGER_CLASS_FUNCTION);
69     }
70
71     /**
72      * @throws UnsupportedOperationException This getter is not supported for writer registry since it does not manage a
73      *                                       specific node type
74      */
75     @Nonnull
76     @Override
77     public InstanceIdentifier<DataObject> getManagedDataObjectType() {
78         throw new UnsupportedOperationException("Root registry has no type");
79     }
80
81     @Override
82     public void update(@Nonnull final InstanceIdentifier<? extends DataObject> id,
83                        @Nullable final DataObject dataBefore,
84                        @Nullable final DataObject dataAfter,
85                        @Nonnull final WriteContext ctx) throws TranslationException {
86         final InstanceIdentifier.PathArgument first = checkNotNull(
87                 Iterables.getFirst(id.getPathArguments(), null), "Empty id");
88         final Writer<? extends DataObject> writer = rootWriters.get(first.getType());
89         checkNotNull(writer,
90                 "Unable to write %s. Missing writer. Current writers for: %s", id, rootWriters.keySet());
91         writer.update(id, dataBefore, dataAfter, ctx);
92     }
93
94     @Override
95     public void update(@Nonnull final Map<InstanceIdentifier<?>, DataObject> nodesBefore,
96                        @Nonnull final Map<InstanceIdentifier<?>, DataObject> nodesAfter,
97                        @Nonnull final WriteContext ctx) throws TranslationException {
98         checkAllWritersPresent(nodesBefore);
99         checkAllWritersPresent(nodesAfter);
100
101         final List<InstanceIdentifier<?>> processedNodes = Lists.newArrayList();
102
103         for (Map.Entry<Class<? extends DataObject>, Writer<? extends DataObject>> rootWriterEntry : rootWriters
104                 .entrySet()) {
105
106             final InstanceIdentifier<? extends DataObject> id = rootWriterEntry.getValue().getManagedDataObjectType();
107
108             final DataObject dataBefore = nodesBefore.get(id);
109             final DataObject dataAfter = nodesAfter.get(id);
110
111             // No change to current writer
112             if (dataBefore == null && dataAfter == null) {
113                 continue;
114             }
115
116             LOG.debug("ChangesProcessor.applyChanges() processing dataBefore={}, dataAfter={}", dataBefore, dataAfter);
117
118             try {
119                 update(id, dataBefore, dataAfter, ctx);
120                 processedNodes.add(id);
121             } catch (Exception e) {
122                 LOG.error("Error while processing data change of: {} (before={}, after={})",
123                         id, dataBefore, dataAfter, e);
124                 throw new BulkUpdateException(
125                         id, new ReverterImpl(this, processedNodes, nodesBefore, nodesAfter, ctx), e);
126             }
127         }
128     }
129
130     private void checkAllWritersPresent(final @Nonnull Map<InstanceIdentifier<?>, DataObject> nodesBefore) {
131         checkArgument(rootWriters.keySet().containsAll(Collections2.transform(nodesBefore.keySet(), ID_TO_CLASS)),
132                 "Unable to handle all changes. Missing dedicated writers for: %s",
133                 Sets.difference(nodesBefore.keySet(), rootWriters.keySet()));
134     }
135
136     private static final class ReverterImpl implements Reverter {
137         private final WriterRegistry delegatingWriterRegistry;
138         private final List<InstanceIdentifier<?>> processedNodes;
139         private final Map<InstanceIdentifier<?>, DataObject> nodesBefore;
140         private final Map<InstanceIdentifier<?>, DataObject> nodesAfter;
141         private final WriteContext ctx;
142
143         ReverterImpl(final WriterRegistry delegatingWriterRegistry,
144                             final List<InstanceIdentifier<?>> processedNodes,
145                             final Map<InstanceIdentifier<?>, DataObject> nodesBefore,
146                             final Map<InstanceIdentifier<?>, DataObject> nodesAfter, final WriteContext ctx) {
147             this.delegatingWriterRegistry = delegatingWriterRegistry;
148             this.processedNodes = processedNodes;
149             this.nodesBefore = nodesBefore;
150             this.nodesAfter = nodesAfter;
151             this.ctx = ctx;
152         }
153
154         @Override
155         public void revert() throws RevertFailedException {
156             final LinkedList<InstanceIdentifier<?>> notReverted = new LinkedList<>(processedNodes);
157
158             while (notReverted.size() > 0) {
159                 final InstanceIdentifier<?> node = notReverted.peekLast();
160                 LOG.debug("ChangesProcessor.revertChanges() processing node={}", node);
161
162                 final DataObject dataBefore = nodesBefore.get(node);
163                 final DataObject dataAfter = nodesAfter.get(node);
164
165                 // revert a change by invoking writer with reordered arguments
166                 try {
167                     delegatingWriterRegistry.update(node, dataAfter, dataBefore, ctx);
168                     notReverted.removeLast(); // change was successfully reverted
169                 } catch (Exception e) {
170                     throw new RevertFailedException(notReverted, e);
171                 }
172
173             }
174         }
175     }
176 }