3b6587a80285a68bdfb22af085506872a8a4ce40
[mdsal.git] / dom / mdsal-dom-broker / src / main / java / org / opendaylight / mdsal / dom / broker / DOMRpcRouter.java
1 /*
2  * Copyright (c) 2015 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.mdsal.dom.broker;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.collect.Collections2;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.ImmutableTable;
19 import com.google.common.collect.MapDifference;
20 import com.google.common.collect.MapDifference.ValueDifference;
21 import com.google.common.collect.Maps;
22 import com.google.common.collect.Sets;
23 import com.google.common.util.concurrent.Futures;
24 import com.google.common.util.concurrent.ListenableFuture;
25 import com.google.common.util.concurrent.ThreadFactoryBuilder;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.HashSet;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.Set;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.ThreadFactory;
36 import javax.annotation.PreDestroy;
37 import javax.inject.Inject;
38 import javax.inject.Singleton;
39 import org.checkerframework.checker.lock.qual.GuardedBy;
40 import org.eclipse.jdt.annotation.NonNull;
41 import org.eclipse.jdt.annotation.NonNullByDefault;
42 import org.opendaylight.mdsal.dom.api.DOMActionAvailabilityExtension;
43 import org.opendaylight.mdsal.dom.api.DOMActionAvailabilityExtension.AvailabilityListener;
44 import org.opendaylight.mdsal.dom.api.DOMActionImplementation;
45 import org.opendaylight.mdsal.dom.api.DOMActionInstance;
46 import org.opendaylight.mdsal.dom.api.DOMActionNotAvailableException;
47 import org.opendaylight.mdsal.dom.api.DOMActionProviderService;
48 import org.opendaylight.mdsal.dom.api.DOMActionResult;
49 import org.opendaylight.mdsal.dom.api.DOMActionService;
50 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
51 import org.opendaylight.mdsal.dom.api.DOMRpcAvailabilityListener;
52 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
53 import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
54 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
55 import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
56 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
57 import org.opendaylight.mdsal.dom.api.DOMRpcService;
58 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
59 import org.opendaylight.yangtools.concepts.AbstractRegistration;
60 import org.opendaylight.yangtools.concepts.Registration;
61 import org.opendaylight.yangtools.yang.common.QName;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
63 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
64 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
65 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
66 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
67 import org.osgi.service.component.annotations.Activate;
68 import org.osgi.service.component.annotations.Component;
69 import org.osgi.service.component.annotations.Deactivate;
70 import org.osgi.service.component.annotations.Reference;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
73
74 @Singleton
75 @Component(service = DOMRpcRouter.class)
76 public final class DOMRpcRouter extends AbstractRegistration implements EffectiveModelContextListener {
77     private static final Logger LOG = LoggerFactory.getLogger(DOMRpcRouter.class);
78     private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder().setNameFormat(
79             "DOMRpcRouter-listener-%s").setDaemon(true).build();
80
81     private final ExecutorService listenerNotifier = Executors.newSingleThreadExecutor(THREAD_FACTORY);
82     private final @NonNull DOMActionProviderService actionProviderService = new ActionProviderServiceFacade();
83     private final @NonNull DOMActionService actionService = new ActionServiceFacade();
84     private final @NonNull DOMRpcProviderService rpcProviderService = new RpcProviderServiceFacade();
85     private final @NonNull DOMRpcService rpcService = new RpcServiceFacade();
86
87     @GuardedBy("this")
88     private ImmutableList<RpcAvailReg> listeners = ImmutableList.of();
89
90     @GuardedBy("this")
91     private ImmutableList<ActionAvailReg> actionListeners = ImmutableList.of();
92
93     private volatile DOMRpcRoutingTable routingTable = DOMRpcRoutingTable.EMPTY;
94
95     private volatile DOMActionRoutingTable actionRoutingTable = DOMActionRoutingTable.EMPTY;
96
97     private Registration listenerRegistration;
98
99     @Deprecated
100     @VisibleForTesting
101     // FIXME: 9.0.0: make this constructor package-private
102     public DOMRpcRouter() {
103
104     }
105
106     @Inject
107     @Activate
108     public DOMRpcRouter(@Reference final DOMSchemaService schemaService) {
109         listenerRegistration = schemaService.registerSchemaContextListener(this);
110         LOG.info("DOM RPC/Action router started");
111     }
112
113     @Deprecated(forRemoval = true)
114     public static DOMRpcRouter newInstance(final DOMSchemaService schemaService) {
115         return new DOMRpcRouter(schemaService);
116     }
117
118     @PreDestroy
119     @Deactivate
120     public void shutdown() {
121         close();
122     }
123
124     public @NonNull DOMActionService actionService() {
125         return actionService;
126     }
127
128     public @NonNull DOMActionProviderService actionProviderService() {
129         return actionProviderService;
130     }
131
132     public @NonNull DOMRpcService rpcService() {
133         return rpcService;
134     }
135
136     public @NonNull DOMRpcProviderService rpcProviderService() {
137         return rpcProviderService;
138     }
139
140     private synchronized void removeRpcImplementation(final DOMRpcImplementation implementation,
141             final Set<DOMRpcIdentifier> rpcs) {
142         final DOMRpcRoutingTable oldTable = routingTable;
143         final DOMRpcRoutingTable newTable = (DOMRpcRoutingTable) oldTable.remove(implementation, rpcs);
144         routingTable = newTable;
145
146         listenerNotifier.execute(() -> notifyRemoved(newTable, implementation));
147     }
148
149     private synchronized void removeRpcImplementations(
150             final ImmutableTable<QName, YangInstanceIdentifier, DOMRpcImplementation> implTable) {
151         final DOMRpcRoutingTable oldTable = routingTable;
152         final DOMRpcRoutingTable newTable = (DOMRpcRoutingTable) oldTable.removeAll(implTable);
153         routingTable = newTable;
154
155         listenerNotifier.execute(() -> notifyRemoved(newTable, implTable.values()));
156     }
157
158     private synchronized void removeActionImplementation(final DOMActionImplementation implementation,
159             final Set<DOMActionInstance> actions) {
160         final DOMActionRoutingTable oldTable = actionRoutingTable;
161         final DOMActionRoutingTable newTable = (DOMActionRoutingTable) oldTable.remove(implementation, actions);
162         actionRoutingTable = newTable;
163
164         listenerNotifier.execute(() -> notifyActionChanged(newTable, implementation));
165     }
166
167     private synchronized void removeListener(final RpcAvailReg reg) {
168         listeners = ImmutableList.copyOf(Collections2.filter(listeners, input -> !reg.equals(input)));
169     }
170
171     private synchronized void removeActionListener(final ActionAvailReg reg) {
172         actionListeners = ImmutableList.copyOf(Collections2.filter(actionListeners, input -> !reg.equals(input)));
173     }
174
175     private synchronized void notifyAdded(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
176         for (var l : listeners) {
177             l.addRpc(newTable, impl);
178         }
179     }
180
181     private synchronized void notifyAdded(final DOMRpcRoutingTable newTable,
182             final Collection<? extends DOMRpcImplementation> impls) {
183         for (var l : listeners) {
184             for (var impl : impls) {
185                 l.addRpc(newTable, impl);
186             }
187         }
188     }
189
190     private synchronized void notifyRemoved(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
191         for (var l : listeners) {
192             l.removeRpc(newTable, impl);
193         }
194     }
195
196     private synchronized void notifyRemoved(final DOMRpcRoutingTable newTable,
197             final Collection<? extends DOMRpcImplementation> impls) {
198         for (var l : listeners) {
199             for (DOMRpcImplementation impl : impls) {
200                 l.removeRpc(newTable, impl);
201             }
202         }
203     }
204
205     private synchronized void notifyActionChanged(final DOMActionRoutingTable newTable,
206             final DOMActionImplementation impl) {
207         for (var l : actionListeners) {
208             l.actionChanged(newTable, impl);
209         }
210     }
211
212     @Override
213     public synchronized void onModelContextUpdated(final EffectiveModelContext newModelContext) {
214         final DOMRpcRoutingTable oldTable = routingTable;
215         final DOMRpcRoutingTable newTable = (DOMRpcRoutingTable) oldTable.setSchemaContext(newModelContext);
216         routingTable = newTable;
217
218         final DOMActionRoutingTable oldActionTable = actionRoutingTable;
219         final DOMActionRoutingTable newActionTable =
220                 (DOMActionRoutingTable) oldActionTable.setSchemaContext(newModelContext);
221         actionRoutingTable = newActionTable;
222     }
223
224     @Override
225     protected void removeRegistration() {
226         if (listenerRegistration != null) {
227             listenerRegistration.close();
228             listenerRegistration = null;
229         }
230         listenerNotifier.shutdown();
231         LOG.info("DOM RPC/Action router stopped");
232     }
233
234     @VisibleForTesting
235     synchronized List<?> listeners() {
236         return listeners;
237     }
238
239     @VisibleForTesting
240     synchronized List<?> actionListeners() {
241         return actionListeners;
242     }
243
244     @VisibleForTesting
245     DOMRpcRoutingTable routingTable() {
246         return routingTable;
247     }
248
249     private static final class RpcAvailReg extends AbstractRegistration {
250         private final DOMRpcAvailabilityListener listener;
251
252         private Map<QName, Set<YangInstanceIdentifier>> prevRpcs;
253         private DOMRpcRouter router;
254
255         RpcAvailReg(final DOMRpcRouter router, final DOMRpcAvailabilityListener listener,
256                 final Map<QName, Set<YangInstanceIdentifier>> rpcs) {
257             this.listener = requireNonNull(listener);
258             this.router = requireNonNull(router);
259             prevRpcs = requireNonNull(rpcs);
260         }
261
262         @Override
263         protected void removeRegistration() {
264             router.removeListener(this);
265             router = null;
266         }
267
268         void initialTable() {
269             final List<DOMRpcIdentifier> added = new ArrayList<>();
270             for (Entry<QName, Set<YangInstanceIdentifier>> e : prevRpcs.entrySet()) {
271                 added.addAll(Collections2.transform(e.getValue(), i -> DOMRpcIdentifier.create(e.getKey(), i)));
272             }
273             if (!added.isEmpty()) {
274                 listener.onRpcAvailable(added);
275             }
276         }
277
278         void addRpc(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
279             if (!listener.acceptsImplementation(impl)) {
280                 return;
281             }
282
283             final Map<QName, Set<YangInstanceIdentifier>> rpcs = verifyNotNull(newTable.getOperations(listener));
284             final MapDifference<QName, Set<YangInstanceIdentifier>> diff = Maps.difference(prevRpcs, rpcs);
285
286             final List<DOMRpcIdentifier> added = new ArrayList<>();
287             for (Entry<QName, Set<YangInstanceIdentifier>> e : diff.entriesOnlyOnRight().entrySet()) {
288                 added.addAll(Collections2.transform(e.getValue(), i -> DOMRpcIdentifier.create(e.getKey(), i)));
289             }
290             for (Entry<QName, ValueDifference<Set<YangInstanceIdentifier>>> e : diff.entriesDiffering().entrySet()) {
291                 for (YangInstanceIdentifier i : Sets.difference(e.getValue().rightValue(), e.getValue().leftValue())) {
292                     added.add(DOMRpcIdentifier.create(e.getKey(), i));
293                 }
294             }
295
296             prevRpcs = rpcs;
297             if (!added.isEmpty()) {
298                 listener.onRpcAvailable(added);
299             }
300         }
301
302         void removeRpc(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
303             if (!listener.acceptsImplementation(impl)) {
304                 return;
305             }
306
307             final Map<QName, Set<YangInstanceIdentifier>> rpcs = verifyNotNull(newTable.getOperations(listener));
308             final MapDifference<QName, Set<YangInstanceIdentifier>> diff = Maps.difference(prevRpcs, rpcs);
309
310             final List<DOMRpcIdentifier> removed = new ArrayList<>();
311             for (Entry<QName, Set<YangInstanceIdentifier>> e : diff.entriesOnlyOnLeft().entrySet()) {
312                 removed.addAll(Collections2.transform(e.getValue(), i -> DOMRpcIdentifier.create(e.getKey(), i)));
313             }
314             for (Entry<QName, ValueDifference<Set<YangInstanceIdentifier>>> e : diff.entriesDiffering().entrySet()) {
315                 for (YangInstanceIdentifier i : Sets.difference(e.getValue().leftValue(), e.getValue().rightValue())) {
316                     removed.add(DOMRpcIdentifier.create(e.getKey(), i));
317                 }
318             }
319
320             prevRpcs = rpcs;
321             if (!removed.isEmpty()) {
322                 listener.onRpcUnavailable(removed);
323             }
324         }
325     }
326
327     private static final class ActionAvailReg extends AbstractRegistration {
328         private final AvailabilityListener listener;
329
330         private Map<Absolute, Set<DOMDataTreeIdentifier>> prevActions;
331         private DOMRpcRouter router;
332
333         ActionAvailReg(final DOMRpcRouter router, final AvailabilityListener listener,
334                 final Map<Absolute, Set<DOMDataTreeIdentifier>> actions) {
335             this.listener = requireNonNull(listener);
336             this.router = requireNonNull(router);
337             prevActions = requireNonNull(actions);
338         }
339
340         @Override
341         protected void removeRegistration() {
342             router.removeActionListener(this);
343             router = null;
344         }
345
346         void initialTable() {
347             final var added = new ArrayList<DOMActionInstance>();
348             for (var e : prevActions.entrySet()) {
349                 added.addAll(Collections2.transform(e.getValue(), i -> DOMActionInstance.of(e.getKey(), i)));
350             }
351             if (!added.isEmpty()) {
352                 listener.onActionsChanged(ImmutableSet.of(), ImmutableSet.copyOf(added));
353             }
354         }
355
356         void actionChanged(final DOMActionRoutingTable newTable, final DOMActionImplementation impl) {
357             if (!listener.acceptsImplementation(impl)) {
358                 return;
359             }
360
361             final Map<Absolute, Set<DOMDataTreeIdentifier>> actions = verifyNotNull(newTable.getOperations(listener));
362             final MapDifference<Absolute, Set<DOMDataTreeIdentifier>> diff = Maps.difference(prevActions, actions);
363
364             final Set<DOMActionInstance> removed = new HashSet<>();
365             final Set<DOMActionInstance> added = new HashSet<>();
366
367             for (Entry<Absolute, Set<DOMDataTreeIdentifier>> e : diff.entriesOnlyOnLeft().entrySet()) {
368                 removed.addAll(Collections2.transform(e.getValue(), i -> DOMActionInstance.of(e.getKey(), i)));
369             }
370
371             for (Entry<Absolute, Set<DOMDataTreeIdentifier>> e : diff.entriesOnlyOnRight().entrySet()) {
372                 added.addAll(Collections2.transform(e.getValue(), i -> DOMActionInstance.of(e.getKey(), i)));
373             }
374
375             for (Entry<Absolute, ValueDifference<Set<DOMDataTreeIdentifier>>> e : diff.entriesDiffering().entrySet()) {
376                 for (DOMDataTreeIdentifier i : Sets.difference(e.getValue().leftValue(), e.getValue().rightValue())) {
377                     removed.add(DOMActionInstance.of(e.getKey(), i));
378                 }
379
380                 for (DOMDataTreeIdentifier i : Sets.difference(e.getValue().rightValue(), e.getValue().leftValue())) {
381                     added.add(DOMActionInstance.of(e.getKey(), i));
382                 }
383             }
384
385             prevActions = actions;
386             if (!removed.isEmpty() || !added.isEmpty()) {
387                 listener.onActionsChanged(removed, added);
388             }
389         }
390     }
391
392     @NonNullByDefault
393     private final class ActionServiceFacade implements DOMActionService, DOMActionAvailabilityExtension {
394         @Override
395         public List<Extension> supportedExtensions() {
396             return List.of(this);
397         }
398
399         @Override
400         public ListenableFuture<? extends DOMActionResult> invokeAction(final Absolute type,
401                 final DOMDataTreeIdentifier path, final ContainerNode input) {
402             final YangInstanceIdentifier pathRoot = path.path();
403             checkArgument(!pathRoot.isEmpty(), "Action path must not be empty");
404
405             final DOMActionRoutingTableEntry entry = (DOMActionRoutingTableEntry) actionRoutingTable.getEntry(type);
406             return entry != null ? OperationInvocation.invoke(entry, type, path, requireNonNull(input))
407                 : Futures.immediateFailedFuture(
408                     new DOMActionNotAvailableException("No implementation of Action %s available", type));
409         }
410
411         @Override
412         public Registration registerAvailabilityListener(final AvailabilityListener listener) {
413             synchronized (DOMRpcRouter.this) {
414                 final var ret = new ActionAvailReg(DOMRpcRouter.this, listener,
415                     actionRoutingTable.getOperations(listener));
416                 actionListeners = ImmutableList.<ActionAvailReg>builder()
417                     .addAll(actionListeners)
418                     .add(ret)
419                     .build();
420
421                 listenerNotifier.execute(ret::initialTable);
422                 return ret;
423             }
424         }
425     }
426
427     @NonNullByDefault
428     private final class ActionProviderServiceFacade implements DOMActionProviderService {
429         @Override
430         public Registration registerActionImplementation(final DOMActionImplementation implementation,
431                 final Set<DOMActionInstance> instances) {
432             checkArgument(!instances.isEmpty(), "Instances must not be empty");
433
434             synchronized (DOMRpcRouter.this) {
435                 final DOMActionRoutingTable oldTable = actionRoutingTable;
436                 final DOMActionRoutingTable newTable = (DOMActionRoutingTable) oldTable.add(implementation, instances);
437                 actionRoutingTable = newTable;
438
439                 listenerNotifier.execute(() -> notifyActionChanged(newTable, implementation));
440             }
441
442             return new AbstractRegistration() {
443                 @Override
444                 protected void removeRegistration() {
445                     removeActionImplementation(implementation, instances);
446                 }
447             };
448         }
449     }
450
451     private final class RpcServiceFacade implements DOMRpcService {
452         @Override
453         public ListenableFuture<? extends DOMRpcResult> invokeRpc(final QName type, final ContainerNode input) {
454             final var entry = (AbstractDOMRpcRoutingTableEntry) routingTable.getEntry(type);
455             if (entry == null) {
456                 return Futures.immediateFailedFuture(
457                     new DOMRpcImplementationNotAvailableException("No implementation of RPC %s available", type));
458             }
459
460             return OperationInvocation.invoke(entry, requireNonNull(input));
461         }
462
463         @Override
464         public Registration registerRpcListener(final DOMRpcAvailabilityListener listener) {
465             synchronized (DOMRpcRouter.this) {
466                 final var ret = new RpcAvailReg(DOMRpcRouter.this, listener, routingTable.getOperations(listener));
467                 listeners = ImmutableList.<RpcAvailReg>builder().addAll(listeners).add(ret).build();
468
469                 listenerNotifier.execute(ret::initialTable);
470                 return ret;
471             }
472         }
473     }
474
475     private final class RpcProviderServiceFacade implements DOMRpcProviderService {
476         @Override
477         public Registration registerRpcImplementation(final DOMRpcImplementation implementation,
478                 final Set<DOMRpcIdentifier> rpcs) {
479
480             synchronized (DOMRpcRouter.this) {
481                 final DOMRpcRoutingTable oldTable = routingTable;
482                 final DOMRpcRoutingTable newTable = (DOMRpcRoutingTable) oldTable.add(implementation, rpcs);
483                 routingTable = newTable;
484
485                 listenerNotifier.execute(() -> notifyAdded(newTable, implementation));
486             }
487
488             return new AbstractRegistration() {
489                 @Override
490                 protected void removeRegistration() {
491                     removeRpcImplementation(implementation, rpcs);
492                 }
493             };
494         }
495
496         @Override
497         public Registration registerRpcImplementations(final Map<DOMRpcIdentifier, DOMRpcImplementation> map) {
498             checkArgument(!map.isEmpty());
499
500             final var builder = ImmutableTable.<QName, YangInstanceIdentifier, DOMRpcImplementation>builder();
501             for (var entry : map.entrySet()) {
502                 final var id = entry.getKey();
503                 builder.put(id.getType(), id.getContextReference(), entry.getValue());
504             }
505             final var implTable = builder.build();
506
507             synchronized (DOMRpcRouter.this) {
508                 final DOMRpcRoutingTable oldTable = routingTable;
509                 final DOMRpcRoutingTable newTable = (DOMRpcRoutingTable) oldTable.addAll(implTable);
510                 routingTable = newTable;
511
512                 listenerNotifier.execute(() -> notifyAdded(newTable, implTable.values()));
513             }
514
515             return new AbstractRegistration() {
516                 @Override
517                 protected void removeRegistration() {
518                     removeRpcImplementations(implTable);
519                 }
520             };
521         }
522     }
523 }