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