Cleanup Throwable catches
[netconf.git] / netconf / netconf-topology-singleton / src / main / java / org / opendaylight / netconf / topology / singleton / impl / actors / NetconfNodeActor.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
9 package org.opendaylight.netconf.topology.singleton.impl.actors;
10
11 import akka.actor.ActorRef;
12 import akka.actor.Props;
13 import akka.actor.UntypedActor;
14 import akka.util.Timeout;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import java.io.IOException;
19 import java.util.List;
20 import java.util.stream.Collectors;
21 import javax.annotation.Nonnull;
22 import javax.annotation.Nullable;
23 import org.opendaylight.controller.cluster.schema.provider.RemoteYangTextSourceProvider;
24 import org.opendaylight.controller.cluster.schema.provider.impl.RemoteSchemaProvider;
25 import org.opendaylight.controller.cluster.schema.provider.impl.YangTextSchemaSourceSerializationProxy;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
29 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
30 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
31 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
32 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
33 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
34 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
35 import org.opendaylight.netconf.topology.singleton.impl.ProxyDOMRpcService;
36 import org.opendaylight.netconf.topology.singleton.impl.ProxyYangTextSourceProvider;
37 import org.opendaylight.netconf.topology.singleton.impl.SlaveSalFacade;
38 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
39 import org.opendaylight.netconf.topology.singleton.messages.AskForMasterMountPoint;
40 import org.opendaylight.netconf.topology.singleton.messages.CreateInitialMasterActorData;
41 import org.opendaylight.netconf.topology.singleton.messages.MasterActorDataInitialized;
42 import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
43 import org.opendaylight.netconf.topology.singleton.messages.RefreshSetupMasterActorData;
44 import org.opendaylight.netconf.topology.singleton.messages.RefreshSlaveActor;
45 import org.opendaylight.netconf.topology.singleton.messages.RegisterMountPoint;
46 import org.opendaylight.netconf.topology.singleton.messages.UnregisterSlaveMountPoint;
47 import org.opendaylight.netconf.topology.singleton.messages.YangTextSchemaSourceRequest;
48 import org.opendaylight.netconf.topology.singleton.messages.rpc.InvokeRpcMessage;
49 import org.opendaylight.netconf.topology.singleton.messages.rpc.InvokeRpcMessageReply;
50 import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyResultResponse;
51 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadTransactionReply;
52 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadTransactionRequest;
53 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadWriteTransactionReply;
54 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadWriteTransactionRequest;
55 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewWriteTransactionReply;
56 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewWriteTransactionRequest;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
58 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
59 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
60 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
61 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
64 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
65 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
66 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
67 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
68 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
69 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72 import scala.concurrent.duration.Duration;
73
74 public class NetconfNodeActor extends UntypedActor {
75
76     private static final Logger LOG = LoggerFactory.getLogger(NetconfNodeActor.class);
77
78     private final Duration writeTxIdleTimeout;
79     private final DOMMountPointService mountPointService;
80
81     private SchemaSourceRegistry schemaRegistry;
82     private SchemaRepository schemaRepository;
83     private Timeout actorResponseWaitTime;
84     private RemoteDeviceId id;
85     private NetconfTopologySetup setup;
86     private List<SourceIdentifier> sourceIdentifiers;
87     private DOMRpcService deviceRpc;
88     private SlaveSalFacade slaveSalManager;
89     private DOMDataBroker deviceDataBroker;
90     //readTxActor can be shared
91     private ActorRef readTxActor;
92     private List<SchemaSourceRegistration<YangTextSchemaSource>> registeredSchemas;
93
94     public static Props props(final NetconfTopologySetup setup,
95                               final RemoteDeviceId id, final SchemaSourceRegistry schemaRegistry,
96                               final SchemaRepository schemaRepository, final Timeout actorResponseWaitTime,
97                               final DOMMountPointService mountPointService) {
98         return Props.create(NetconfNodeActor.class, () ->
99                 new NetconfNodeActor(setup, id, schemaRegistry, schemaRepository, actorResponseWaitTime,
100                         mountPointService));
101     }
102
103     private NetconfNodeActor(final NetconfTopologySetup setup,
104                              final RemoteDeviceId id, final SchemaSourceRegistry schemaRegistry,
105                              final SchemaRepository schemaRepository, final Timeout actorResponseWaitTime,
106                              final DOMMountPointService mountPointService) {
107         this.setup = setup;
108         this.id = id;
109         this.schemaRegistry = schemaRegistry;
110         this.schemaRepository = schemaRepository;
111         this.actorResponseWaitTime = actorResponseWaitTime;
112         this.writeTxIdleTimeout = setup.getIdleTimeout();
113         this.mountPointService = mountPointService;
114     }
115
116     @SuppressWarnings("checkstyle:IllegalCatch")
117     @Override
118     public void onReceive(final Object message) throws Exception {
119         if (message instanceof CreateInitialMasterActorData) { // master
120
121             final CreateInitialMasterActorData masterActorData = (CreateInitialMasterActorData) message;
122             sourceIdentifiers = masterActorData.getSourceIndentifiers();
123             this.deviceDataBroker = masterActorData.getDeviceDataBroker();
124             final DOMDataReadOnlyTransaction tx = deviceDataBroker.newReadOnlyTransaction();
125             readTxActor = context().actorOf(ReadTransactionActor.props(tx));
126             this.deviceRpc = masterActorData.getDeviceRpc();
127
128             sender().tell(new MasterActorDataInitialized(), self());
129
130             LOG.debug("{}: Master is ready.", id);
131
132         } else if (message instanceof  RefreshSetupMasterActorData) {
133             setup = ((RefreshSetupMasterActorData) message).getNetconfTopologyDeviceSetup();
134             id = ((RefreshSetupMasterActorData) message).getRemoteDeviceId();
135             sender().tell(new MasterActorDataInitialized(), self());
136         } else if (message instanceof AskForMasterMountPoint) { // master
137             // only master contains reference to deviceDataBroker
138             if (deviceDataBroker != null) {
139                 getSender().tell(new RegisterMountPoint(sourceIdentifiers), getSelf());
140             }
141
142         } else if (message instanceof YangTextSchemaSourceRequest) { // master
143
144             final YangTextSchemaSourceRequest yangTextSchemaSourceRequest = (YangTextSchemaSourceRequest) message;
145             sendYangTextSchemaSourceProxy(yangTextSchemaSourceRequest.getSourceIdentifier(), sender());
146
147         } else if (message instanceof NewReadTransactionRequest) { // master
148
149             sender().tell(new NewReadTransactionReply(readTxActor), self());
150
151         } else if (message instanceof NewWriteTransactionRequest) { // master
152             try {
153                 final DOMDataWriteTransaction tx = deviceDataBroker.newWriteOnlyTransaction();
154                 final ActorRef txActor = context().actorOf(WriteTransactionActor.props(tx, writeTxIdleTimeout));
155                 sender().tell(new NewWriteTransactionReply(txActor), self());
156             } catch (final Exception t) {
157                 sender().tell(t, self());
158             }
159
160         } else if (message instanceof NewReadWriteTransactionRequest) {
161             try {
162                 final DOMDataReadWriteTransaction tx = deviceDataBroker.newReadWriteTransaction();
163                 final ActorRef txActor = context().actorOf(ReadWriteTransactionActor.props(tx, writeTxIdleTimeout));
164                 sender().tell(new NewReadWriteTransactionReply(txActor), self());
165             } catch (final Exception t) {
166                 sender().tell(t, self());
167             }
168         } else if (message instanceof InvokeRpcMessage) { // master
169
170             final InvokeRpcMessage invokeRpcMessage = ((InvokeRpcMessage) message);
171             invokeSlaveRpc(invokeRpcMessage.getSchemaPath(), invokeRpcMessage.getNormalizedNodeMessage(), sender());
172
173         } else if (message instanceof RegisterMountPoint) { //slaves
174
175             sourceIdentifiers = ((RegisterMountPoint) message).getSourceIndentifiers();
176             registerSlaveMountPoint(getSender());
177
178         } else if (message instanceof UnregisterSlaveMountPoint) { //slaves
179             if (slaveSalManager != null) {
180                 slaveSalManager.close();
181                 slaveSalManager = null;
182             }
183         } else if (message instanceof RefreshSlaveActor) { //slave
184             actorResponseWaitTime = ((RefreshSlaveActor) message).getActorResponseWaitTime();
185             id = ((RefreshSlaveActor) message).getId();
186             schemaRegistry = ((RefreshSlaveActor) message).getSchemaRegistry();
187             setup = ((RefreshSlaveActor) message).getSetup();
188             schemaRepository = ((RefreshSlaveActor) message).getSchemaRepository();
189         }
190
191     }
192
193     @Override
194     public void postStop() throws Exception {
195         super.postStop();
196         closeSchemaSourceRegistrations();
197     }
198
199     private void sendYangTextSchemaSourceProxy(final SourceIdentifier sourceIdentifier, final ActorRef sender) {
200         final CheckedFuture<YangTextSchemaSource, SchemaSourceException> yangTextSchemaSource =
201                 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
202
203         Futures.addCallback(yangTextSchemaSource, new FutureCallback<YangTextSchemaSource>() {
204             @Override
205             public void onSuccess(final YangTextSchemaSource yangTextSchemaSource) {
206                 try {
207                     sender.tell(new YangTextSchemaSourceSerializationProxy(yangTextSchemaSource), getSelf());
208                 } catch (final IOException exception) {
209                     sender.tell(exception.getCause(), getSelf());
210                 }
211             }
212
213             @Override
214             public void onFailure(@Nonnull final Throwable throwable) {
215                 sender.tell(throwable, getSelf());
216             }
217         });
218     }
219
220     private void invokeSlaveRpc(final SchemaPath schemaPath, final NormalizedNodeMessage normalizedNodeMessage,
221                                 final ActorRef recipient) {
222
223         final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResult =
224                 deviceRpc.invokeRpc(schemaPath, normalizedNodeMessage.getNode());
225
226         Futures.addCallback(rpcResult, new FutureCallback<DOMRpcResult>() {
227             @Override
228             public void onSuccess(@Nullable final DOMRpcResult domRpcResult) {
229                 if (domRpcResult == null) {
230                     recipient.tell(new EmptyResultResponse(), getSender());
231                     return;
232                 }
233                 NormalizedNodeMessage nodeMessageReply = null;
234                 if (domRpcResult.getResult() != null) {
235                     nodeMessageReply = new NormalizedNodeMessage(YangInstanceIdentifier.EMPTY,
236                             domRpcResult.getResult());
237                 }
238                 recipient.tell(new InvokeRpcMessageReply(nodeMessageReply, domRpcResult.getErrors()), getSelf());
239             }
240
241             @Override
242             public void onFailure(@Nonnull final Throwable throwable) {
243                 recipient.tell(throwable, getSelf());
244             }
245         });
246     }
247
248     private void registerSlaveMountPoint(final ActorRef masterReference) {
249         if (this.slaveSalManager != null) {
250             slaveSalManager.close();
251         }
252         closeSchemaSourceRegistrations();
253         slaveSalManager = new SlaveSalFacade(id, setup.getActorSystem(), actorResponseWaitTime,
254                 mountPointService);
255
256         final CheckedFuture<SchemaContext, SchemaResolutionException> remoteSchemaContext =
257                 getSchemaContext(masterReference);
258         final DOMRpcService deviceRpc = getDOMRpcService(masterReference);
259
260         Futures.addCallback(remoteSchemaContext, new FutureCallback<SchemaContext>() {
261             @Override
262             public void onSuccess(final SchemaContext result) {
263                 LOG.info("{}: Schema context resolved: {}", id, result.getModules());
264                 slaveSalManager.registerSlaveMountPoint(result, deviceRpc, masterReference);
265             }
266
267             @Override
268             public void onFailure(@Nonnull final Throwable throwable) {
269                 LOG.error("{}: Failed to register mount point: {}", id, throwable);
270             }
271         });
272     }
273
274     private DOMRpcService getDOMRpcService(final ActorRef masterReference) {
275         return new ProxyDOMRpcService(setup.getActorSystem(), masterReference, id, actorResponseWaitTime);
276     }
277
278     private CheckedFuture<SchemaContext, SchemaResolutionException> getSchemaContext(final ActorRef masterReference) {
279
280         final RemoteYangTextSourceProvider remoteYangTextSourceProvider =
281                 new ProxyYangTextSourceProvider(masterReference, getContext(), actorResponseWaitTime);
282         final RemoteSchemaProvider remoteProvider = new RemoteSchemaProvider(remoteYangTextSourceProvider,
283                 getContext().dispatcher());
284
285         registeredSchemas = sourceIdentifiers.stream()
286                 .map(sourceId ->
287                         schemaRegistry.registerSchemaSource(remoteProvider, PotentialSchemaSource.create(sourceId,
288                                 YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())))
289                 .collect(Collectors.toList());
290
291         final SchemaContextFactory schemaContextFactory
292                 = schemaRepository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
293
294         return schemaContextFactory.createSchemaContext(sourceIdentifiers);
295     }
296
297     private void closeSchemaSourceRegistrations() {
298         if (registeredSchemas != null) {
299             registeredSchemas.forEach(SchemaSourceRegistration::close);
300             registeredSchemas = null;
301         }
302     }
303
304 }