HONEYCOMB-61: Detect VPP disconnect using keepalives
[honeycomb.git] / v3po / translate-utils / src / main / java / io / fd / honeycomb / v3po / translate / util / write / DelegatingWriterRegistry.java
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.util.RWUtils;
28 import io.fd.honeycomb.v3po.translate.write.WriteContext;
29 import io.fd.honeycomb.v3po.translate.write.WriteFailedException;
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 java.util.Set;
36 import javax.annotation.Nonnull;
37 import javax.annotation.Nullable;
38 import org.opendaylight.yangtools.yang.binding.DataObject;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * Simple writer registry able to perform and aggregated write (ROOT write) on top of all provided writers. Also able to
45  * delegate a specific write to one of the delegate writers.
46  *
47  * This could serve as a utility to hold & hide all available writers in upper layers.
48  */
49 public final class DelegatingWriterRegistry implements WriterRegistry {
50
51     private static final Logger LOG = LoggerFactory.getLogger(DelegatingWriterRegistry.class);
52
53     private final Map<Class<? extends DataObject>, Writer<? extends DataObject>> rootWriters;
54
55     /**
56      * Create new {@link DelegatingWriterRegistry}
57      *
58      * @param rootWriters List of delegate writers
59      */
60     public DelegatingWriterRegistry(@Nonnull final List<Writer<? extends DataObject>> rootWriters) {
61         this.rootWriters = RWUtils.uniqueLinkedIndex(checkNotNull(rootWriters), RWUtils.MANAGER_CLASS_FUNCTION);
62     }
63
64     /**
65      * @throws UnsupportedOperationException This getter is not supported for writer registry since it does not manage a
66      *                                       specific node type
67      */
68     @Nonnull
69     @Override
70     public InstanceIdentifier<DataObject> getManagedDataObjectType() {
71         throw new UnsupportedOperationException("Root registry has no type");
72     }
73
74     @Override
75     public void update(@Nonnull final InstanceIdentifier<? extends DataObject> id,
76                        @Nullable final DataObject dataBefore,
77                        @Nullable final DataObject dataAfter,
78                        @Nonnull final WriteContext ctx) throws WriteFailedException {
79         final InstanceIdentifier.PathArgument first = checkNotNull(
80                 Iterables.getFirst(id.getPathArguments(), null), "Empty id");
81         final Writer<? extends DataObject> writer = rootWriters.get(first.getType());
82         checkNotNull(writer,
83                 "Unable to write %s. Missing writer. Current writers for: %s", id, rootWriters.keySet());
84         writer.update(id, dataBefore, dataAfter, ctx);
85     }
86
87     @Override
88     public void update(@Nonnull final Map<InstanceIdentifier<?>, DataObject> nodesBefore,
89                        @Nonnull final Map<InstanceIdentifier<?>, DataObject> nodesAfter,
90                        @Nonnull final WriteContext ctx) throws WriteFailedException {
91         checkAllWritersPresent(nodesBefore);
92         checkAllWritersPresent(nodesAfter);
93
94         final List<InstanceIdentifier<?>> processedNodes = Lists.newArrayList();
95
96         for (Map.Entry<Class<? extends DataObject>, Writer<? extends DataObject>> rootWriterEntry : rootWriters
97                 .entrySet()) {
98
99             final InstanceIdentifier<? extends DataObject> id = rootWriterEntry.getValue().getManagedDataObjectType();
100
101             final DataObject dataBefore = nodesBefore.get(id);
102             final DataObject dataAfter = nodesAfter.get(id);
103
104             // No change to current writer
105             if (dataBefore == null && dataAfter == null) {
106                 continue;
107             }
108
109             LOG.debug("ChangesProcessor.applyChanges() processing dataBefore={}, dataAfter={}", dataBefore, dataAfter);
110
111             try {
112                 update(id, dataBefore, dataAfter, ctx);
113                 processedNodes.add(id);
114             } catch (Exception e) {
115                 LOG.error("Error while processing data change of: {} (before={}, after={})",
116                         id, dataBefore, dataAfter, e);
117                 throw new BulkUpdateException(
118                         id, new ReverterImpl(this, processedNodes, nodesBefore, nodesAfter, ctx), e);
119             }
120         }
121     }
122
123     private void checkAllWritersPresent(final @Nonnull Map<InstanceIdentifier<?>, DataObject> nodesBefore) {
124         final Set<Class<? extends DataObject>> nodesBeforeClasses =
125             Sets.newHashSet(Collections2.transform(nodesBefore.keySet(),
126                 (Function<InstanceIdentifier<?>, Class<? extends DataObject>>) InstanceIdentifier::getTargetType));
127         checkArgument(rootWriters.keySet().containsAll(nodesBeforeClasses),
128                 "Unable to handle all changes. Missing dedicated writers for: %s",
129                 Sets.difference(nodesBeforeClasses, rootWriters.keySet()));
130     }
131
132     private static final class ReverterImpl implements Reverter {
133         private final WriterRegistry delegatingWriterRegistry;
134         private final List<InstanceIdentifier<?>> processedNodes;
135         private final Map<InstanceIdentifier<?>, DataObject> nodesBefore;
136         private final Map<InstanceIdentifier<?>, DataObject> nodesAfter;
137         private final WriteContext ctx;
138
139         ReverterImpl(final WriterRegistry delegatingWriterRegistry,
140                             final List<InstanceIdentifier<?>> processedNodes,
141                             final Map<InstanceIdentifier<?>, DataObject> nodesBefore,
142                             final Map<InstanceIdentifier<?>, DataObject> nodesAfter, final WriteContext ctx) {
143             this.delegatingWriterRegistry = delegatingWriterRegistry;
144             this.processedNodes = processedNodes;
145             this.nodesBefore = nodesBefore;
146             this.nodesAfter = nodesAfter;
147             this.ctx = ctx;
148         }
149
150         @Override
151         public void revert() throws RevertFailedException {
152             final LinkedList<InstanceIdentifier<?>> notReverted = new LinkedList<>(processedNodes);
153
154             while (notReverted.size() > 0) {
155                 final InstanceIdentifier<?> node = notReverted.peekLast();
156                 LOG.debug("ChangesProcessor.revertChanges() processing node={}", node);
157
158                 final DataObject dataBefore = nodesBefore.get(node);
159                 final DataObject dataAfter = nodesAfter.get(node);
160
161                 // revert a change by invoking writer with reordered arguments
162                 try {
163                     delegatingWriterRegistry.update(node, dataAfter, dataBefore, ctx);
164                     notReverted.removeLast(); // change was successfully reverted
165                 } catch (Exception e) {
166                     throw new RevertFailedException(notReverted, e);
167                 }
168
169             }
170         }
171     }
172 }