Merge "Convert ProxyDOMDataBroker tx creation to async"
[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.Status.Failure;
14 import akka.actor.Status.Success;
15 import akka.pattern.AskTimeoutException;
16 import akka.util.Timeout;
17 import com.google.common.base.Throwables;
18 import com.google.common.util.concurrent.CheckedFuture;
19 import com.google.common.util.concurrent.FutureCallback;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.ListenableFuture;
22 import com.google.common.util.concurrent.MoreExecutors;
23 import java.io.IOException;
24 import java.util.List;
25 import java.util.stream.Collectors;
26 import javax.annotation.Nonnull;
27 import javax.annotation.Nullable;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedActor;
30 import org.opendaylight.controller.cluster.schema.provider.RemoteYangTextSourceProvider;
31 import org.opendaylight.controller.cluster.schema.provider.impl.RemoteSchemaProvider;
32 import org.opendaylight.controller.cluster.schema.provider.impl.YangTextSchemaSourceSerializationProxy;
33 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
34 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
35 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
36 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
37 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
38 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
39 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
40 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
41 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
42 import org.opendaylight.netconf.topology.singleton.impl.ProxyDOMRpcService;
43 import org.opendaylight.netconf.topology.singleton.impl.ProxyYangTextSourceProvider;
44 import org.opendaylight.netconf.topology.singleton.impl.SlaveSalFacade;
45 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
46 import org.opendaylight.netconf.topology.singleton.messages.AskForMasterMountPoint;
47 import org.opendaylight.netconf.topology.singleton.messages.CreateInitialMasterActorData;
48 import org.opendaylight.netconf.topology.singleton.messages.MasterActorDataInitialized;
49 import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
50 import org.opendaylight.netconf.topology.singleton.messages.NotMasterException;
51 import org.opendaylight.netconf.topology.singleton.messages.RefreshSetupMasterActorData;
52 import org.opendaylight.netconf.topology.singleton.messages.RefreshSlaveActor;
53 import org.opendaylight.netconf.topology.singleton.messages.RegisterMountPoint;
54 import org.opendaylight.netconf.topology.singleton.messages.UnregisterSlaveMountPoint;
55 import org.opendaylight.netconf.topology.singleton.messages.YangTextSchemaSourceRequest;
56 import org.opendaylight.netconf.topology.singleton.messages.rpc.InvokeRpcMessage;
57 import org.opendaylight.netconf.topology.singleton.messages.rpc.InvokeRpcMessageReply;
58 import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyResultResponse;
59 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadTransactionRequest;
60 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadWriteTransactionRequest;
61 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewWriteTransactionRequest;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
64 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
65 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
66 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
67 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
68 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
69 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
70 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
71 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
72 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
73 import scala.concurrent.duration.Duration;
74
75 public class NetconfNodeActor extends AbstractUntypedActor {
76
77     private final Duration writeTxIdleTimeout;
78     private final DOMMountPointService mountPointService;
79
80     private SchemaSourceRegistry schemaRegistry;
81     private SchemaRepository schemaRepository;
82     private Timeout actorResponseWaitTime;
83     private RemoteDeviceId id;
84     private NetconfTopologySetup setup;
85     private List<SourceIdentifier> sourceIdentifiers;
86     private DOMRpcService deviceRpc;
87     private SlaveSalFacade slaveSalManager;
88     private DOMDataBroker deviceDataBroker;
89     //readTxActor can be shared
90     private ActorRef readTxActor;
91     private List<SchemaSourceRegistration<YangTextSchemaSource>> registeredSchemas;
92
93     public static Props props(final NetconfTopologySetup setup,
94                               final RemoteDeviceId id, final SchemaSourceRegistry schemaRegistry,
95                               final SchemaRepository schemaRepository, final Timeout actorResponseWaitTime,
96                               final DOMMountPointService mountPointService) {
97         return Props.create(NetconfNodeActor.class, () ->
98                 new NetconfNodeActor(setup, id, schemaRegistry, schemaRepository, actorResponseWaitTime,
99                         mountPointService));
100     }
101
102     protected NetconfNodeActor(final NetconfTopologySetup setup,
103                                final RemoteDeviceId id, final SchemaSourceRegistry schemaRegistry,
104                                final SchemaRepository schemaRepository, final Timeout actorResponseWaitTime,
105                                final DOMMountPointService mountPointService) {
106         this.setup = setup;
107         this.id = id;
108         this.schemaRegistry = schemaRegistry;
109         this.schemaRepository = schemaRepository;
110         this.actorResponseWaitTime = actorResponseWaitTime;
111         this.writeTxIdleTimeout = setup.getIdleTimeout();
112         this.mountPointService = mountPointService;
113     }
114
115     @SuppressWarnings("checkstyle:IllegalCatch")
116     @Override
117     public void handleReceive(final Object message) throws Exception {
118         LOG.debug("{}:  received message {}", id, message);
119
120         if (message instanceof CreateInitialMasterActorData) { // master
121
122             final CreateInitialMasterActorData masterActorData = (CreateInitialMasterActorData) message;
123             sourceIdentifiers = masterActorData.getSourceIndentifiers();
124             this.deviceDataBroker = masterActorData.getDeviceDataBroker();
125             final DOMDataReadOnlyTransaction tx = deviceDataBroker.newReadOnlyTransaction();
126             readTxActor = context().actorOf(ReadTransactionActor.props(tx));
127             this.deviceRpc = masterActorData.getDeviceRpc();
128
129             sender().tell(new MasterActorDataInitialized(), self());
130
131             LOG.debug("{}: Master is ready.", id);
132
133         } else if (message instanceof  RefreshSetupMasterActorData) {
134             setup = ((RefreshSetupMasterActorData) message).getNetconfTopologyDeviceSetup();
135             id = ((RefreshSetupMasterActorData) message).getRemoteDeviceId();
136             sender().tell(new MasterActorDataInitialized(), self());
137         } else if (message instanceof AskForMasterMountPoint) { // master
138             AskForMasterMountPoint askForMasterMountPoint = (AskForMasterMountPoint)message;
139
140             // only master contains reference to deviceDataBroker
141             if (deviceDataBroker != null) {
142                 LOG.debug("{}: Sending RegisterMountPoint reply to {}", id, askForMasterMountPoint.getSlaveActorRef());
143                 askForMasterMountPoint.getSlaveActorRef().tell(new RegisterMountPoint(sourceIdentifiers, self()),
144                         sender());
145             } else {
146                 LOG.warn("{}: Received {} but we don't appear to be the master", id, askForMasterMountPoint);
147                 sender().tell(new Failure(new NotMasterException(self())), self());
148             }
149
150         } else if (message instanceof YangTextSchemaSourceRequest) { // master
151
152             final YangTextSchemaSourceRequest yangTextSchemaSourceRequest = (YangTextSchemaSourceRequest) message;
153             sendYangTextSchemaSourceProxy(yangTextSchemaSourceRequest.getSourceIdentifier(), sender());
154
155         } else if (message instanceof NewReadTransactionRequest) { // master
156             sender().tell(new Success(readTxActor), self());
157         } else if (message instanceof NewWriteTransactionRequest) { // master
158             try {
159                 final DOMDataWriteTransaction tx = deviceDataBroker.newWriteOnlyTransaction();
160                 final ActorRef txActor = context().actorOf(WriteTransactionActor.props(tx, writeTxIdleTimeout));
161                 sender().tell(new Success(txActor), self());
162             } catch (final Exception t) {
163                 sender().tell(new Failure(t), self());
164             }
165
166         } else if (message instanceof NewReadWriteTransactionRequest) {
167             try {
168                 final DOMDataReadWriteTransaction tx = deviceDataBroker.newReadWriteTransaction();
169                 final ActorRef txActor = context().actorOf(ReadWriteTransactionActor.props(tx, writeTxIdleTimeout));
170                 sender().tell(new Success(txActor), self());
171             } catch (final Exception t) {
172                 sender().tell(new Failure(t), self());
173             }
174         } else if (message instanceof InvokeRpcMessage) { // master
175             final InvokeRpcMessage invokeRpcMessage = (InvokeRpcMessage) message;
176             invokeSlaveRpc(invokeRpcMessage.getSchemaPath(), invokeRpcMessage.getNormalizedNodeMessage(), sender());
177
178         } else if (message instanceof RegisterMountPoint) { //slaves
179             RegisterMountPoint registerMountPoint = (RegisterMountPoint)message;
180             sourceIdentifiers = registerMountPoint.getSourceIndentifiers();
181             registerSlaveMountPoint(registerMountPoint.getMasterActorRef());
182             sender().tell(new Success(null), self());
183         } else if (message instanceof UnregisterSlaveMountPoint) { //slaves
184             unregisterSlaveMountPoint();
185         } else if (message instanceof RefreshSlaveActor) { //slave
186             actorResponseWaitTime = ((RefreshSlaveActor) message).getActorResponseWaitTime();
187             id = ((RefreshSlaveActor) message).getId();
188             schemaRegistry = ((RefreshSlaveActor) message).getSchemaRegistry();
189             setup = ((RefreshSlaveActor) message).getSetup();
190             schemaRepository = ((RefreshSlaveActor) message).getSchemaRepository();
191         }
192
193     }
194
195     @Override
196     public void postStop() throws Exception {
197         try {
198             super.postStop();
199         } finally {
200             unregisterSlaveMountPoint();
201         }
202     }
203
204     private void unregisterSlaveMountPoint() {
205         if (slaveSalManager != null) {
206             slaveSalManager.close();
207             slaveSalManager = null;
208         }
209
210         closeSchemaSourceRegistrations();
211     }
212
213     private void sendYangTextSchemaSourceProxy(final SourceIdentifier sourceIdentifier, final ActorRef sender) {
214         final ListenableFuture<@NonNull YangTextSchemaSource> schemaSourceFuture =
215                 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
216
217         Futures.addCallback(schemaSourceFuture, new FutureCallback<YangTextSchemaSource>() {
218             @Override
219             public void onSuccess(final YangTextSchemaSource yangTextSchemaSource) {
220                 try {
221                     LOG.debug("{}: getSchemaSource for {} succeeded", id, sourceIdentifier);
222                     sender.tell(new YangTextSchemaSourceSerializationProxy(yangTextSchemaSource), getSelf());
223                 } catch (IOException e) {
224                     sender.tell(new Failure(e), getSelf());
225                 }
226             }
227
228             @Override
229             public void onFailure(@Nonnull final Throwable throwable) {
230                 LOG.debug("{}: getSchemaSource for {} failed", id, sourceIdentifier, throwable);
231                 sender.tell(new Failure(throwable), getSelf());
232             }
233         }, MoreExecutors.directExecutor());
234     }
235
236     private void invokeSlaveRpc(final SchemaPath schemaPath, final NormalizedNodeMessage normalizedNodeMessage,
237                                 final ActorRef recipient) {
238
239         LOG.debug("{}: invokeSlaveRpc for {}, input: {} on rpc service {}", id, schemaPath, normalizedNodeMessage,
240                 deviceRpc);
241
242         final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResult = deviceRpc.invokeRpc(schemaPath,
243                 normalizedNodeMessage != null ? normalizedNodeMessage.getNode() : null);
244
245         Futures.addCallback(rpcResult, new FutureCallback<DOMRpcResult>() {
246             @Override
247             public void onSuccess(@Nullable final DOMRpcResult domRpcResult) {
248                 LOG.debug("{}: invokeSlaveRpc for {}, domRpcResult: {}", id, schemaPath, domRpcResult);
249
250                 if (domRpcResult == null) {
251                     recipient.tell(new EmptyResultResponse(), getSender());
252                     return;
253                 }
254                 NormalizedNodeMessage nodeMessageReply = null;
255                 if (domRpcResult.getResult() != null) {
256                     nodeMessageReply = new NormalizedNodeMessage(YangInstanceIdentifier.EMPTY,
257                             domRpcResult.getResult());
258                 }
259                 recipient.tell(new InvokeRpcMessageReply(nodeMessageReply, domRpcResult.getErrors()), getSelf());
260             }
261
262             @Override
263             public void onFailure(@Nonnull final Throwable throwable) {
264                 recipient.tell(new Failure(throwable), getSelf());
265             }
266         }, MoreExecutors.directExecutor());
267     }
268
269     private void registerSlaveMountPoint(final ActorRef masterReference) {
270         unregisterSlaveMountPoint();
271
272         slaveSalManager = new SlaveSalFacade(id, setup.getActorSystem(), actorResponseWaitTime, mountPointService);
273
274         resolveSchemaContext(createSchemaContextFactory(masterReference), slaveSalManager, masterReference, 1);
275     }
276
277     private DOMRpcService getDOMRpcService(final ActorRef masterReference) {
278         return new ProxyDOMRpcService(setup.getActorSystem(), masterReference, id, actorResponseWaitTime);
279     }
280
281     private SchemaContextFactory createSchemaContextFactory(final ActorRef masterReference) {
282         final RemoteYangTextSourceProvider remoteYangTextSourceProvider =
283                 new ProxyYangTextSourceProvider(masterReference, getContext().dispatcher(), actorResponseWaitTime);
284         final RemoteSchemaProvider remoteProvider = new RemoteSchemaProvider(remoteYangTextSourceProvider,
285                 getContext().dispatcher());
286
287         registeredSchemas = sourceIdentifiers.stream()
288                 .map(sourceId ->
289                         schemaRegistry.registerSchemaSource(remoteProvider, PotentialSchemaSource.create(sourceId,
290                                 YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())))
291                 .collect(Collectors.toList());
292
293         return schemaRepository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
294     }
295
296     private void resolveSchemaContext(final SchemaContextFactory schemaContextFactory,
297             final SlaveSalFacade localSlaveSalManager, final ActorRef masterReference, int tries) {
298         final ListenableFuture<SchemaContext> schemaContextFuture =
299                 schemaContextFactory.createSchemaContext(sourceIdentifiers);
300         Futures.addCallback(schemaContextFuture, new FutureCallback<SchemaContext>() {
301             @Override
302             public void onSuccess(@Nonnull final SchemaContext result) {
303                 executeInSelf(() -> {
304                     // Make sure the slaveSalManager instance hasn't changed since we initiated the schema context
305                     // resolution.
306                     if (slaveSalManager == localSlaveSalManager) {
307                         LOG.info("{}: Schema context resolved: {} - registering slave mount point",
308                                 id, result.getModules());
309                         slaveSalManager.registerSlaveMountPoint(result, getDOMRpcService(masterReference),
310                                 masterReference);
311                     }
312                 });
313             }
314
315             @Override
316             public void onFailure(@Nonnull final Throwable throwable) {
317                 executeInSelf(() -> {
318                     if (slaveSalManager == localSlaveSalManager) {
319                         final Throwable cause = Throwables.getRootCause(throwable);
320                         if (cause instanceof AskTimeoutException) {
321                             if (tries <= 5 || tries % 10 == 0) {
322                                 LOG.warn("{}: Failed to resolve schema context - retrying...", id, throwable);
323                             }
324
325                             resolveSchemaContext(schemaContextFactory, localSlaveSalManager,
326                                     masterReference, tries + 1);
327                         } else {
328                             LOG.error("{}: Failed to resolve schema context - unable to register slave mount point",
329                                     id, throwable);
330                             closeSchemaSourceRegistrations();
331                         }
332                     }
333                 });
334             }
335         }, MoreExecutors.directExecutor());
336     }
337
338     private void closeSchemaSourceRegistrations() {
339         if (registeredSchemas != null) {
340             registeredSchemas.forEach(SchemaSourceRegistration::close);
341             registeredSchemas = null;
342         }
343     }
344
345 }