2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.netconf.topology.singleton.impl.actors;
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;
75 public class NetconfNodeActor extends AbstractUntypedActor {
77 private final Duration writeTxIdleTimeout;
78 private final DOMMountPointService mountPointService;
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;
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,
102 protected NetconfNodeActor(final NetconfTopologySetup setup,
103 final RemoteDeviceId id, final SchemaSourceRegistry schemaRegistry,
104 final SchemaRepository schemaRepository, final Timeout actorResponseWaitTime,
105 final DOMMountPointService mountPointService) {
108 this.schemaRegistry = schemaRegistry;
109 this.schemaRepository = schemaRepository;
110 this.actorResponseWaitTime = actorResponseWaitTime;
111 this.writeTxIdleTimeout = setup.getIdleTimeout();
112 this.mountPointService = mountPointService;
115 @SuppressWarnings("checkstyle:IllegalCatch")
117 public void handleReceive(final Object message) throws Exception {
118 LOG.debug("{}: received message {}", id, message);
120 if (message instanceof CreateInitialMasterActorData) { // master
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();
129 sender().tell(new MasterActorDataInitialized(), self());
131 LOG.debug("{}: Master is ready.", id);
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;
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()),
146 LOG.warn("{}: Received {} but we don't appear to be the master", id, askForMasterMountPoint);
147 sender().tell(new Failure(new NotMasterException(self())), self());
150 } else if (message instanceof YangTextSchemaSourceRequest) { // master
152 final YangTextSchemaSourceRequest yangTextSchemaSourceRequest = (YangTextSchemaSourceRequest) message;
153 sendYangTextSchemaSourceProxy(yangTextSchemaSourceRequest.getSourceIdentifier(), sender());
155 } else if (message instanceof NewReadTransactionRequest) { // master
156 sender().tell(new Success(readTxActor), self());
157 } else if (message instanceof NewWriteTransactionRequest) { // master
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());
166 } else if (message instanceof NewReadWriteTransactionRequest) {
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());
174 } else if (message instanceof InvokeRpcMessage) { // master
175 final InvokeRpcMessage invokeRpcMessage = (InvokeRpcMessage) message;
176 invokeSlaveRpc(invokeRpcMessage.getSchemaPath(), invokeRpcMessage.getNormalizedNodeMessage(), sender());
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();
196 public void postStop() throws Exception {
200 unregisterSlaveMountPoint();
204 private void unregisterSlaveMountPoint() {
205 if (slaveSalManager != null) {
206 slaveSalManager.close();
207 slaveSalManager = null;
210 closeSchemaSourceRegistrations();
213 private void sendYangTextSchemaSourceProxy(final SourceIdentifier sourceIdentifier, final ActorRef sender) {
214 final ListenableFuture<@NonNull YangTextSchemaSource> schemaSourceFuture =
215 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
217 Futures.addCallback(schemaSourceFuture, new FutureCallback<YangTextSchemaSource>() {
219 public void onSuccess(final YangTextSchemaSource yangTextSchemaSource) {
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());
229 public void onFailure(@Nonnull final Throwable throwable) {
230 LOG.debug("{}: getSchemaSource for {} failed", id, sourceIdentifier, throwable);
231 sender.tell(new Failure(throwable), getSelf());
233 }, MoreExecutors.directExecutor());
236 private void invokeSlaveRpc(final SchemaPath schemaPath, final NormalizedNodeMessage normalizedNodeMessage,
237 final ActorRef recipient) {
239 LOG.debug("{}: invokeSlaveRpc for {}, input: {} on rpc service {}", id, schemaPath, normalizedNodeMessage,
242 final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResult = deviceRpc.invokeRpc(schemaPath,
243 normalizedNodeMessage != null ? normalizedNodeMessage.getNode() : null);
245 Futures.addCallback(rpcResult, new FutureCallback<DOMRpcResult>() {
247 public void onSuccess(@Nullable final DOMRpcResult domRpcResult) {
248 LOG.debug("{}: invokeSlaveRpc for {}, domRpcResult: {}", id, schemaPath, domRpcResult);
250 if (domRpcResult == null) {
251 recipient.tell(new EmptyResultResponse(), getSender());
254 NormalizedNodeMessage nodeMessageReply = null;
255 if (domRpcResult.getResult() != null) {
256 nodeMessageReply = new NormalizedNodeMessage(YangInstanceIdentifier.EMPTY,
257 domRpcResult.getResult());
259 recipient.tell(new InvokeRpcMessageReply(nodeMessageReply, domRpcResult.getErrors()), getSelf());
263 public void onFailure(@Nonnull final Throwable throwable) {
264 recipient.tell(new Failure(throwable), getSelf());
266 }, MoreExecutors.directExecutor());
269 private void registerSlaveMountPoint(final ActorRef masterReference) {
270 unregisterSlaveMountPoint();
272 slaveSalManager = new SlaveSalFacade(id, setup.getActorSystem(), actorResponseWaitTime, mountPointService);
274 resolveSchemaContext(createSchemaContextFactory(masterReference), slaveSalManager, masterReference, 1);
277 private DOMRpcService getDOMRpcService(final ActorRef masterReference) {
278 return new ProxyDOMRpcService(setup.getActorSystem(), masterReference, id, actorResponseWaitTime);
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());
287 registeredSchemas = sourceIdentifiers.stream()
289 schemaRegistry.registerSchemaSource(remoteProvider, PotentialSchemaSource.create(sourceId,
290 YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())))
291 .collect(Collectors.toList());
293 return schemaRepository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
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>() {
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
306 if (slaveSalManager == localSlaveSalManager) {
307 LOG.info("{}: Schema context resolved: {} - registering slave mount point",
308 id, result.getModules());
309 slaveSalManager.registerSlaveMountPoint(result, getDOMRpcService(masterReference),
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);
325 resolveSchemaContext(schemaContextFactory, localSlaveSalManager,
326 masterReference, tries + 1);
328 LOG.error("{}: Failed to resolve schema context - unable to register slave mount point",
330 closeSchemaSourceRegistrations();
335 }, MoreExecutors.directExecutor());
338 private void closeSchemaSourceRegistrations() {
339 if (registeredSchemas != null) {
340 registeredSchemas.forEach(SchemaSourceRegistration::close);
341 registeredSchemas = null;