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