Convert ProxyDOMDataBroker tx creation to async
[netconf.git] / netconf / netconf-topology-singleton / src / main / java / org / opendaylight / netconf / topology / singleton / impl / MasterSalFacade.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;
10
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSystem;
13 import akka.cluster.Cluster;
14 import akka.dispatch.OnComplete;
15 import akka.pattern.Patterns;
16 import akka.util.Timeout;
17 import com.google.common.base.Preconditions;
18 import java.util.List;
19 import java.util.stream.Collectors;
20 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
21 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
22 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
23 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
24 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
25 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
26 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
27 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
28 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceDataBroker;
29 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceNotificationService;
30 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceSalProvider;
31 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
32 import org.opendaylight.netconf.topology.singleton.messages.CreateInitialMasterActorData;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
34 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
35 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
36 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import scala.concurrent.Future;
40
41 class MasterSalFacade implements AutoCloseable, RemoteDeviceHandler<NetconfSessionPreferences> {
42
43     private static final Logger LOG = LoggerFactory.getLogger(MasterSalFacade.class);
44
45     private final RemoteDeviceId id;
46     private final Timeout actorResponseWaitTime;
47     private final NetconfDeviceSalProvider salProvider;
48     private final ActorRef masterActorRef;
49     private final ActorSystem actorSystem;
50
51     private SchemaContext currentSchemaContext = null;
52     private NetconfSessionPreferences netconfSessionPreferences = null;
53     private DOMRpcService deviceRpc = null;
54     private DOMDataBroker deviceDataBroker = null;
55
56     MasterSalFacade(final RemoteDeviceId id,
57                     final ActorSystem actorSystem,
58                     final ActorRef masterActorRef,
59                     final Timeout actorResponseWaitTime,
60                     final DOMMountPointService mountService,
61                     final DataBroker dataBroker) {
62         this.id = id;
63         this.salProvider = new NetconfDeviceSalProvider(id, mountService, dataBroker);
64         this.actorSystem = actorSystem;
65         this.masterActorRef = masterActorRef;
66         this.actorResponseWaitTime = actorResponseWaitTime;
67     }
68
69     @Override
70     public void onDeviceConnected(final SchemaContext remoteSchemaContext,
71                                   final NetconfSessionPreferences sessionPreferences,
72                                   final DOMRpcService domRpcService) {
73         this.currentSchemaContext = remoteSchemaContext;
74         this.netconfSessionPreferences = sessionPreferences;
75         this.deviceRpc = domRpcService;
76
77         LOG.info("Device {} connected - registering master mount point", id);
78
79         registerMasterMountPoint();
80
81         sendInitialDataToActor().onComplete(new OnComplete<Object>() {
82             @Override
83             public void onComplete(final Throwable failure, final Object success) {
84                 if (failure == null) {
85                     updateDeviceData();
86                     return;
87                 }
88
89                 LOG.error("{}: CreateInitialMasterActorData to {} failed", id, masterActorRef, failure);
90             }
91         }, actorSystem.dispatcher());
92
93     }
94
95     @Override
96     public void onDeviceDisconnected() {
97         LOG.info("Device {} disconnected - unregistering master mount point", id);
98         salProvider.getTopologyDatastoreAdapter().updateDeviceData(false, new NetconfDeviceCapabilities());
99         unregisterMasterMountPoint();
100     }
101
102     @Override
103     public void onDeviceFailed(final Throwable throwable) {
104         salProvider.getTopologyDatastoreAdapter().setDeviceAsFailed(throwable);
105         unregisterMasterMountPoint();
106     }
107
108     @Override
109     public void onNotification(final DOMNotification domNotification) {
110         salProvider.getMountInstance().publish(domNotification);
111     }
112
113     @Override
114     public void close() {
115         unregisterMasterMountPoint();
116         closeGracefully(salProvider);
117     }
118
119     private void registerMasterMountPoint() {
120         Preconditions.checkNotNull(id);
121         Preconditions.checkNotNull(currentSchemaContext,
122                 "Device has no remote schema context yet. Probably not fully connected.");
123         Preconditions.checkNotNull(netconfSessionPreferences,
124                 "Device has no capabilities yet. Probably not fully connected.");
125
126         final NetconfDeviceNotificationService notificationService = new NetconfDeviceNotificationService();
127
128         deviceDataBroker = newDeviceDataBroker();
129
130         // We need to create ProxyDOMDataBroker so accessing mountpoint
131         // on leader node would be same as on follower node
132         final ProxyDOMDataBroker proxyDataBroker =
133                 new ProxyDOMDataBroker(id, masterActorRef, actorSystem.dispatcher(), actorResponseWaitTime);
134         salProvider.getMountInstance()
135                 .onTopologyDeviceConnected(currentSchemaContext, proxyDataBroker, deviceRpc, notificationService);
136     }
137
138     protected DOMDataBroker newDeviceDataBroker() {
139         return new NetconfDeviceDataBroker(id, currentSchemaContext, deviceRpc, netconfSessionPreferences);
140     }
141
142     private Future<Object> sendInitialDataToActor() {
143         final List<SourceIdentifier> sourceIdentifiers =
144                 SchemaContextUtil.getConstituentModuleIdentifiers(currentSchemaContext).stream()
145                 .map(mi -> RevisionSourceIdentifier.create(mi.getName(), mi.getRevision()))
146                 .collect(Collectors.toList());
147
148         LOG.debug("{}: Sending CreateInitialMasterActorData with sourceIdentifiers {} to {}",
149                 id, sourceIdentifiers, masterActorRef);
150
151         // send initial data to master actor
152         return Patterns.ask(masterActorRef, new CreateInitialMasterActorData(deviceDataBroker, sourceIdentifiers,
153                 deviceRpc), actorResponseWaitTime);
154     }
155
156     private void updateDeviceData() {
157         final String masterAddress = Cluster.get(actorSystem).selfAddress().toString();
158         LOG.debug("{}: updateDeviceData with master address {}", id, masterAddress);
159         salProvider.getTopologyDatastoreAdapter().updateClusteredDeviceData(true, masterAddress,
160                 netconfSessionPreferences.getNetconfDeviceCapabilities());
161     }
162
163     private void unregisterMasterMountPoint() {
164         salProvider.getMountInstance().onTopologyDeviceDisconnected();
165     }
166
167     @SuppressWarnings("checkstyle:IllegalCatch")
168     private void closeGracefully(final AutoCloseable resource) {
169         if (resource != null) {
170             try {
171                 resource.close();
172             } catch (final Exception e) {
173                 LOG.error("{}: Ignoring exception while closing {}", id, resource, e);
174             }
175         }
176     }
177
178 }