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
8 package org.opendaylight.netconf.topology.singleton.impl.actors;
10 import akka.actor.ActorRef;
11 import akka.actor.Props;
12 import akka.actor.Status.Failure;
13 import akka.actor.Status.Success;
14 import akka.pattern.AskTimeoutException;
15 import akka.util.Timeout;
16 import com.google.common.base.Throwables;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.MoreExecutors;
21 import java.io.IOException;
22 import java.util.List;
23 import java.util.stream.Collectors;
24 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedActor;
25 import org.opendaylight.controller.cluster.schema.provider.RemoteYangTextSourceProvider;
26 import org.opendaylight.controller.cluster.schema.provider.impl.RemoteSchemaProvider;
27 import org.opendaylight.controller.cluster.schema.provider.impl.YangTextSchemaSourceSerializationProxy;
28 import org.opendaylight.mdsal.dom.api.DOMActionResult;
29 import org.opendaylight.mdsal.dom.api.DOMActionService;
30 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
31 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
32 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
33 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
34 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
35 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
36 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
37 import org.opendaylight.mdsal.dom.api.DOMRpcService;
38 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
39 import org.opendaylight.netconf.topology.singleton.impl.ProxyDOMActionService;
40 import org.opendaylight.netconf.topology.singleton.impl.ProxyDOMRpcService;
41 import org.opendaylight.netconf.topology.singleton.impl.ProxyYangTextSourceProvider;
42 import org.opendaylight.netconf.topology.singleton.impl.SlaveSalFacade;
43 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
44 import org.opendaylight.netconf.topology.singleton.messages.AskForMasterMountPoint;
45 import org.opendaylight.netconf.topology.singleton.messages.ContainerNodeMessage;
46 import org.opendaylight.netconf.topology.singleton.messages.CreateInitialMasterActorData;
47 import org.opendaylight.netconf.topology.singleton.messages.MasterActorDataInitialized;
48 import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
49 import org.opendaylight.netconf.topology.singleton.messages.NotMasterException;
50 import org.opendaylight.netconf.topology.singleton.messages.RefreshSetupMasterActorData;
51 import org.opendaylight.netconf.topology.singleton.messages.RefreshSlaveActor;
52 import org.opendaylight.netconf.topology.singleton.messages.RegisterMountPoint;
53 import org.opendaylight.netconf.topology.singleton.messages.UnregisterSlaveMountPoint;
54 import org.opendaylight.netconf.topology.singleton.messages.YangTextSchemaSourceRequest;
55 import org.opendaylight.netconf.topology.singleton.messages.action.InvokeActionMessage;
56 import org.opendaylight.netconf.topology.singleton.messages.action.InvokeActionMessageReply;
57 import org.opendaylight.netconf.topology.singleton.messages.rpc.InvokeRpcMessage;
58 import org.opendaylight.netconf.topology.singleton.messages.rpc.InvokeRpcMessageReply;
59 import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyResultResponse;
60 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadTransactionRequest;
61 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadWriteTransactionRequest;
62 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewWriteTransactionRequest;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
67 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
68 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
69 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
70 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
71 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
72 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
73 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
74 import scala.concurrent.duration.Duration;
76 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 DOMActionService deviceAction;
88 private SlaveSalFacade slaveSalManager;
89 private DOMDataBroker deviceDataBroker;
90 //readTxActor can be shared
91 private ActorRef readTxActor;
92 private List<SchemaSourceRegistration<YangTextSchemaSource>> registeredSchemas;
94 public static Props props(final NetconfTopologySetup setup, final RemoteDeviceId id,
95 final Timeout actorResponseWaitTime, final DOMMountPointService mountPointService) {
96 return Props.create(NetconfNodeActor.class, () ->
97 new NetconfNodeActor(setup, id, actorResponseWaitTime, mountPointService));
100 protected NetconfNodeActor(final NetconfTopologySetup setup,
101 final RemoteDeviceId id, final Timeout actorResponseWaitTime,
102 final DOMMountPointService mountPointService) {
105 this.schemaRegistry = setup.getSchemaResourcesDTO().getSchemaRegistry();
106 this.schemaRepository = setup.getSchemaResourcesDTO().getSchemaRepository();
107 this.actorResponseWaitTime = actorResponseWaitTime;
108 this.writeTxIdleTimeout = setup.getIdleTimeout();
109 this.mountPointService = mountPointService;
112 @SuppressWarnings("checkstyle:IllegalCatch")
114 public void handleReceive(final Object message) {
115 LOG.debug("{}: received message {}", id, message);
117 if (message instanceof CreateInitialMasterActorData) { // master
119 final CreateInitialMasterActorData masterActorData = (CreateInitialMasterActorData) message;
120 sourceIdentifiers = masterActorData.getSourceIndentifiers();
121 this.deviceDataBroker = masterActorData.getDeviceDataBroker();
122 final DOMDataTreeReadTransaction tx = deviceDataBroker.newReadOnlyTransaction();
123 readTxActor = context().actorOf(ReadTransactionActor.props(tx));
124 this.deviceRpc = masterActorData.getDeviceRpc();
125 this.deviceAction = masterActorData.getDeviceAction();
127 sender().tell(new MasterActorDataInitialized(), self());
129 LOG.debug("{}: Master is ready.", id);
131 } else if (message instanceof RefreshSetupMasterActorData) {
132 setup = ((RefreshSetupMasterActorData) message).getNetconfTopologyDeviceSetup();
133 id = ((RefreshSetupMasterActorData) message).getRemoteDeviceId();
134 sender().tell(new MasterActorDataInitialized(), self());
135 } else if (message instanceof AskForMasterMountPoint) { // master
136 AskForMasterMountPoint askForMasterMountPoint = (AskForMasterMountPoint) message;
138 // only master contains reference to deviceDataBroker
139 if (deviceDataBroker != null) {
140 LOG.debug("{}: Sending RegisterMountPoint reply to {}", id, askForMasterMountPoint.getSlaveActorRef());
141 askForMasterMountPoint.getSlaveActorRef().tell(new RegisterMountPoint(sourceIdentifiers, self()),
144 LOG.warn("{}: Received {} but we don't appear to be the master", id, askForMasterMountPoint);
145 sender().tell(new Failure(new NotMasterException(self())), self());
148 } else if (message instanceof YangTextSchemaSourceRequest) { // master
150 final YangTextSchemaSourceRequest yangTextSchemaSourceRequest = (YangTextSchemaSourceRequest) message;
151 sendYangTextSchemaSourceProxy(yangTextSchemaSourceRequest.getSourceIdentifier(), sender());
153 } else if (message instanceof NewReadTransactionRequest) { // master
154 sender().tell(new Success(readTxActor), self());
155 } else if (message instanceof NewWriteTransactionRequest) { // master
157 final DOMDataTreeWriteTransaction tx = deviceDataBroker.newWriteOnlyTransaction();
158 final ActorRef txActor = context().actorOf(WriteTransactionActor.props(tx, writeTxIdleTimeout));
159 sender().tell(new Success(txActor), self());
160 } catch (final Exception t) {
161 sender().tell(new Failure(t), self());
164 } else if (message instanceof NewReadWriteTransactionRequest) {
166 final DOMDataTreeReadWriteTransaction tx = deviceDataBroker.newReadWriteTransaction();
167 final ActorRef txActor = context().actorOf(ReadWriteTransactionActor.props(tx, writeTxIdleTimeout));
168 sender().tell(new Success(txActor), self());
169 } catch (final Exception t) {
170 sender().tell(new Failure(t), self());
172 } else if (message instanceof InvokeRpcMessage) { // master
173 final InvokeRpcMessage invokeRpcMessage = (InvokeRpcMessage) message;
174 invokeSlaveRpc(invokeRpcMessage.getSchemaPath(), invokeRpcMessage.getNormalizedNodeMessage(), sender());
175 } else if (message instanceof InvokeActionMessage) { // master
176 final InvokeActionMessage invokeActionMessage = (InvokeActionMessage) message;
177 LOG.info("InvokeActionMessage Details : {}", invokeActionMessage.toString());
178 invokeSlaveAction(invokeActionMessage.getSchemaPath(), invokeActionMessage.getContainerNodeMessage(),
179 invokeActionMessage.getDOMDataTreeIdentifier(), sender());
180 } else if (message instanceof RegisterMountPoint) { //slaves
181 RegisterMountPoint registerMountPoint = (RegisterMountPoint) message;
182 sourceIdentifiers = registerMountPoint.getSourceIndentifiers();
183 registerSlaveMountPoint(registerMountPoint.getMasterActorRef());
184 sender().tell(new Success(null), self());
185 } else if (message instanceof UnregisterSlaveMountPoint) { //slaves
186 unregisterSlaveMountPoint();
187 } else if (message instanceof RefreshSlaveActor) { //slave
188 actorResponseWaitTime = ((RefreshSlaveActor) message).getActorResponseWaitTime();
189 id = ((RefreshSlaveActor) message).getId();
190 schemaRegistry = ((RefreshSlaveActor) message).getSchemaRegistry();
191 setup = ((RefreshSlaveActor) message).getSetup();
192 schemaRepository = ((RefreshSlaveActor) message).getSchemaRepository();
197 public void postStop() throws Exception {
201 unregisterSlaveMountPoint();
205 private void unregisterSlaveMountPoint() {
206 if (slaveSalManager != null) {
207 slaveSalManager.close();
208 slaveSalManager = null;
211 closeSchemaSourceRegistrations();
214 private void sendYangTextSchemaSourceProxy(final SourceIdentifier sourceIdentifier, final ActorRef sender) {
215 final ListenableFuture<YangTextSchemaSource> schemaSourceFuture =
216 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
218 Futures.addCallback(schemaSourceFuture, new FutureCallback<YangTextSchemaSource>() {
220 public void onSuccess(final YangTextSchemaSource yangTextSchemaSource) {
222 LOG.debug("{}: getSchemaSource for {} succeeded", id, sourceIdentifier);
223 sender.tell(new YangTextSchemaSourceSerializationProxy(yangTextSchemaSource), getSelf());
224 } catch (IOException e) {
225 sender.tell(new Failure(e), getSelf());
230 public void onFailure(final Throwable throwable) {
231 LOG.debug("{}: getSchemaSource for {} failed", id, sourceIdentifier, throwable);
232 sender.tell(new Failure(throwable), getSelf());
234 }, MoreExecutors.directExecutor());
237 private void invokeSlaveRpc(final SchemaPath schemaPath, final NormalizedNodeMessage normalizedNodeMessage,
238 final ActorRef recipient) {
240 LOG.debug("{}: invokeSlaveRpc for {}, input: {} on rpc service {}", id, schemaPath, normalizedNodeMessage,
243 final ListenableFuture<DOMRpcResult> rpcResult = deviceRpc.invokeRpc(schemaPath,
244 normalizedNodeMessage != null ? normalizedNodeMessage.getNode() : null);
246 Futures.addCallback(rpcResult, new FutureCallback<DOMRpcResult>() {
248 public void onSuccess(final DOMRpcResult domRpcResult) {
249 LOG.debug("{}: invokeSlaveRpc for {}, domRpcResult: {}", id, schemaPath, domRpcResult);
251 if (domRpcResult == null) {
252 recipient.tell(new EmptyResultResponse(), getSender());
255 NormalizedNodeMessage nodeMessageReply = null;
256 if (domRpcResult.getResult() != null) {
257 nodeMessageReply = new NormalizedNodeMessage(YangInstanceIdentifier.EMPTY,
258 domRpcResult.getResult());
260 recipient.tell(new InvokeRpcMessageReply(nodeMessageReply, domRpcResult.getErrors()), getSelf());
264 public void onFailure(final Throwable throwable) {
265 recipient.tell(new Failure(throwable), getSelf());
267 }, MoreExecutors.directExecutor());
271 * Invoking Action on Slave Node in Odl Cluster Environment.
273 * @param schemaPath {@link SchemaPath}
274 * @param containerNodeMessage {@link ContainerNodeMessage}
275 * @param domDataTreeIdentifier {@link DOMDataTreeIdentifier}
276 * @param recipient {@link ActorRef}
278 private void invokeSlaveAction(final SchemaPath schemaPath, final ContainerNodeMessage containerNodeMessage,
279 final DOMDataTreeIdentifier domDataTreeIdentifier, final ActorRef recipient) {
280 LOG.info("{}: invokeSlaveAction for {}, input: {}, identifier: {} on action service {}", id, schemaPath,
281 containerNodeMessage, domDataTreeIdentifier, deviceAction);
283 final ListenableFuture<? extends DOMActionResult> actionResult = deviceAction.invokeAction(schemaPath,
284 domDataTreeIdentifier, containerNodeMessage != null ? containerNodeMessage.getNode() : null);
286 Futures.addCallback(actionResult, new FutureCallback<DOMActionResult>() {
289 public void onSuccess(final DOMActionResult domActionResult) {
290 LOG.debug("{}: invokeSlaveAction for {}, domActionResult: {}", id, schemaPath, domActionResult);
291 if (domActionResult == null) {
292 recipient.tell(new EmptyResultResponse(), getSender());
296 //Check DomActionResult containing Ok onSuccess pass empty nodeMessageReply
297 ContainerNodeMessage nodeMessageReply = domActionResult.getOutput().map(ContainerNodeMessage::new)
299 recipient.tell(new InvokeActionMessageReply(nodeMessageReply, domActionResult.getErrors()), getSelf());
303 public void onFailure(final Throwable throwable) {
304 recipient.tell(new Failure(throwable), getSelf());
306 }, MoreExecutors.directExecutor());
309 private void registerSlaveMountPoint(final ActorRef masterReference) {
310 unregisterSlaveMountPoint();
312 slaveSalManager = new SlaveSalFacade(id, setup.getActorSystem(), actorResponseWaitTime, mountPointService);
314 resolveSchemaContext(createSchemaContextFactory(masterReference), slaveSalManager, masterReference, 1);
317 private DOMRpcService getDOMRpcService(final ActorRef masterReference) {
318 return new ProxyDOMRpcService(setup.getActorSystem(), masterReference, id, actorResponseWaitTime);
321 private DOMActionService getDOMActionService(final ActorRef masterReference) {
322 return new ProxyDOMActionService(setup.getActorSystem(), masterReference, id, actorResponseWaitTime);
325 private EffectiveModelContextFactory createSchemaContextFactory(final ActorRef masterReference) {
326 final RemoteYangTextSourceProvider remoteYangTextSourceProvider =
327 new ProxyYangTextSourceProvider(masterReference, getContext().dispatcher(), actorResponseWaitTime);
328 final RemoteSchemaProvider remoteProvider = new RemoteSchemaProvider(remoteYangTextSourceProvider,
329 getContext().dispatcher());
331 registeredSchemas = sourceIdentifiers.stream()
333 schemaRegistry.registerSchemaSource(remoteProvider, PotentialSchemaSource.create(sourceId,
334 YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())))
335 .collect(Collectors.toList());
337 return schemaRepository.createEffectiveModelContextFactory();
340 private void resolveSchemaContext(final EffectiveModelContextFactory schemaContextFactory,
341 final SlaveSalFacade localSlaveSalManager, final ActorRef masterReference, final int tries) {
342 final ListenableFuture<EffectiveModelContext> schemaContextFuture =
343 schemaContextFactory.createEffectiveModelContext(sourceIdentifiers);
344 Futures.addCallback(schemaContextFuture, new FutureCallback<SchemaContext>() {
346 public void onSuccess(final SchemaContext result) {
347 executeInSelf(() -> {
348 // Make sure the slaveSalManager instance hasn't changed since we initiated the schema context
350 if (slaveSalManager == localSlaveSalManager) {
351 LOG.info("{}: Schema context resolved: {} - registering slave mount point",
352 id, result.getModules());
353 slaveSalManager.registerSlaveMountPoint(result, getDOMRpcService(masterReference),
354 getDOMActionService(masterReference), masterReference);
360 public void onFailure(final Throwable throwable) {
361 executeInSelf(() -> {
362 if (slaveSalManager == localSlaveSalManager) {
363 final Throwable cause = Throwables.getRootCause(throwable);
364 if (cause instanceof AskTimeoutException) {
365 if (tries <= 5 || tries % 10 == 0) {
366 LOG.warn("{}: Failed to resolve schema context - retrying...", id, throwable);
369 resolveSchemaContext(schemaContextFactory, localSlaveSalManager,
370 masterReference, tries + 1);
372 LOG.error("{}: Failed to resolve schema context - unable to register slave mount point",
374 closeSchemaSourceRegistrations();
379 }, MoreExecutors.directExecutor());
382 private void closeSchemaSourceRegistrations() {
383 if (registeredSchemas != null) {
384 registeredSchemas.forEach(SchemaSourceRegistration::close);
385 registeredSchemas = null;