a1305dbab201017820ae49e818a1873df8eb5c07
[netconf.git] / netconf / netconf-topology-singleton / src / main / java / org / opendaylight / netconf / topology / singleton / impl / actors / WriteTransactionActor.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies s.r.o. 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.Props;
12 import akka.actor.ReceiveTimeout;
13 import akka.actor.UntypedActor;
14 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
15 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
16 import org.opendaylight.netconf.topology.singleton.messages.transactions.WriteActorMessage;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19 import scala.concurrent.duration.Duration;
20
21 /**
22  * WriteTransactionActor is an interface to device's {@link DOMDataReadOnlyTransaction} for cluster nodes.
23  */
24 public final class WriteTransactionActor extends UntypedActor {
25
26     private static final Logger LOG = LoggerFactory.getLogger(WriteTransactionActor.class);
27
28     private final DOMDataWriteTransaction tx;
29     private final long idleTimeout;
30     private final WriteAdapter writeAdapter;
31
32     private WriteTransactionActor(final DOMDataWriteTransaction tx, final Duration idleTimeout) {
33         this.tx = tx;
34         this.idleTimeout = idleTimeout.toSeconds();
35         if (this.idleTimeout > 0) {
36             context().setReceiveTimeout(idleTimeout);
37         }
38         writeAdapter = new WriteAdapter(tx);
39     }
40
41     /**
42      * Creates new actor Props.
43      *
44      * @param tx          delegate device write transaction
45      * @param idleTimeout idle time in seconds, after which transaction is closed automatically
46      * @return props
47      */
48     static Props props(final DOMDataWriteTransaction tx, final Duration idleTimeout) {
49         return Props.create(WriteTransactionActor.class, () -> new WriteTransactionActor(tx, idleTimeout));
50     }
51
52     @Override
53     public void onReceive(final Object message) throws Throwable {
54         if (message instanceof WriteActorMessage) {
55             writeAdapter.handle(message, sender(), context(), self());
56         } else if (message instanceof ReceiveTimeout) {
57             LOG.warn("Haven't received any message for {} seconds, cancelling transaction and stopping actor",
58                     idleTimeout);
59             tx.cancel();
60             context().stop(self());
61         } else {
62             unhandled(message);
63         }
64     }
65
66
67 }