Merge "Add Unit tests"
[ccsdk/features.git] / sdnr / wt / devicemanager / provider / src / main / java / org / onap / ccsdk / features / sdnr / wt / devicemanager / impl / DeviceManagerImpl.java
1 /*******************************************************************************
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl;
19
20 import java.util.List;
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.CopyOnWriteArrayList;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation;
26 import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataProvider;
27 import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.IEntityDataProvider;
28 import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.IEsConfig;
29 import org.onap.ccsdk.features.sdnr.wt.devicemanager.aaiconnector.impl.AaiProviderClient;
30 import org.onap.ccsdk.features.sdnr.wt.devicemanager.archiveservice.ArchiveCleanService;
31 import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeForwarderImpl;
32 import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeForwarderInternal;
33 import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeProviderClient;
34 import org.onap.ccsdk.features.sdnr.wt.devicemanager.devicemonitor.impl.DeviceMonitor;
35 import org.onap.ccsdk.features.sdnr.wt.devicemanager.devicemonitor.impl.DeviceMonitorImpl;
36 import org.onap.ccsdk.features.sdnr.wt.devicemanager.eventdatahandler.DeviceManagerDatabaseNotificationService;
37 import org.onap.ccsdk.features.sdnr.wt.devicemanager.eventdatahandler.ODLEventListenerHandler;
38 import org.onap.ccsdk.features.sdnr.wt.devicemanager.eventdatahandler.RpcPushNotificationsHandler;
39 import org.onap.ccsdk.features.sdnr.wt.devicemanager.housekeeping.ConnectionStatusHousekeepingService;
40 import org.onap.ccsdk.features.sdnr.wt.devicemanager.housekeeping.ResyncNetworkElementHouskeepingService;
41 import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.WebSocketServiceClientImpl2;
42 import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.WebSocketServiceClientInternal;
43 import org.onap.ccsdk.features.sdnr.wt.devicemanager.maintenance.impl.MaintenanceServiceImpl;
44 import org.onap.ccsdk.features.sdnr.wt.devicemanager.ne.factory.FactoryRegistration;
45 import org.onap.ccsdk.features.sdnr.wt.devicemanager.ne.factory.NetworkElementFactory;
46 import org.onap.ccsdk.features.sdnr.wt.devicemanager.ne.service.NetworkElement;
47 import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.PerformanceManagerImpl;
48 import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.service.MicrowaveHistoricalPerformanceWriterService;
49 import org.onap.ccsdk.features.sdnr.wt.devicemanager.service.AaiService;
50 import org.onap.ccsdk.features.sdnr.wt.devicemanager.service.DeviceManagerServiceProvider;
51 import org.onap.ccsdk.features.sdnr.wt.devicemanager.service.EquipmentService;
52 import org.onap.ccsdk.features.sdnr.wt.devicemanager.service.EventHandlingService;
53 import org.onap.ccsdk.features.sdnr.wt.devicemanager.service.FaultService;
54 import org.onap.ccsdk.features.sdnr.wt.devicemanager.service.MaintenanceService;
55 import org.onap.ccsdk.features.sdnr.wt.devicemanager.service.NetconfNetworkElementService;
56 import org.onap.ccsdk.features.sdnr.wt.devicemanager.service.NotificationService;
57 import org.onap.ccsdk.features.sdnr.wt.devicemanager.service.PerformanceManager;
58 import org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter.DevicemanagerNotificationDelayService;
59 import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.NetconfNodeStateService;
60 import org.opendaylight.mdsal.binding.api.DataBroker;
61 import org.opendaylight.mdsal.binding.api.MountPoint;
62 import org.opendaylight.mdsal.binding.api.MountPointService;
63 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
64 import org.opendaylight.mdsal.binding.api.RpcProviderService;
65 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
66 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.websocketmanager.rev150105.WebsocketmanagerService;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71 /**
72  * Devicemanager
73  * - Handles startup and closedown of network element handlers for netconf session
74  * - Provide common services for network element specific components
75  */
76 public class DeviceManagerImpl implements NetconfNetworkElementService, DeviceManagerServiceProvider, AutoCloseable {
77
78     private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerImpl.class);
79     private static final String APPLICATION_NAME = "DeviceManager";
80     private static final String MYDBKEYNAMEBASE = "SDN-Controller";
81     private static final String CONFIGURATIONFILE = "etc/devicemanager.properties";
82     public static final long DATABASE_TIMEOUT_MS = 120*1000L;
83
84     @SuppressWarnings("unused")
85     private static final String STARTUPLOG_FILENAME = "etc/devicemanager.startup.log";
86     // private static final String STARTUPLOG_FILENAME2 = "data/cache/devicemanager.startup.log";
87
88     // MDSAL Services
89     private DataBroker dataBroker;
90     private MountPointService mountPointService;
91     private RpcProviderService rpcProviderRegistry;
92     @SuppressWarnings("unused")
93     private NotificationPublishService notificationPublishService;
94     private ClusterSingletonServiceProvider clusterSingletonServiceProvider;
95     private WebsocketmanagerService websocketmanagerService;
96     private IEntityDataProvider iEntityDataProvider;
97
98     // Devicemanager common services for network element handler
99     private @Nullable WebSocketServiceClientInternal webSocketService;
100     private ODLEventListenerHandler odlEventListenerHandler; //EventHandlingService
101     //private NetconfChangeListener netconfChangeListener;
102     private DeviceManagerApiServiceImpl rpcApiService;
103     private PerformanceManagerImpl performanceManager;
104     private DcaeProviderClient dcaeProviderClient;
105     private AaiProviderClient aaiProviderClient;
106     private DcaeForwarderInternal aotsDcaeForwarder;
107     private DeviceMonitor deviceMonitor;
108     private MaintenanceServiceImpl maintenanceService;
109     private DevicemanagerNotificationDelayService notificationDelayService;
110     private ResyncNetworkElementHouskeepingService resyncNetworkElementHouskeepingService;
111     private ArchiveCleanService archiveCleanService;
112     private ConnectionStatusHousekeepingService housekeepingService;
113     private NetconfNodeStateService netconfNodeStateService;
114     private DataProvider dataProvider;
115     //private HtDatabaseClient htDatabaseClient;
116     // Handler
117     private RpcPushNotificationsHandler rpcPushNotificationsHandler;
118     private DeviceManagerNetconfConnectHandler forTest;
119     // Attributes
120     private final Object networkelementLock;
121     private final ConcurrentHashMap<String, NetworkElement> networkElementRepresentations;
122     private final List<MyNetworkElementFactory<? extends NetworkElementFactory>> factoryList;
123
124     private DeviceManagerDatabaseNotificationService deviceManagerDatabaseAndNotificationService;
125     private ClusterSingletonServiceRegistration cssRegistration;
126     private ClusterSingletonServiceRegistration cssRegistration2;
127
128
129     private Boolean devicemanagerInitializationOk;
130
131     // Blueprint 1
132     public DeviceManagerImpl() {
133         LOG.info("Creating provider for {}", APPLICATION_NAME);
134         this.devicemanagerInitializationOk = false;
135         this.factoryList = new CopyOnWriteArrayList<>();
136         this.networkelementLock = new Object();
137         this.networkElementRepresentations = new ConcurrentHashMap<>();
138
139         this.dataBroker = null;
140         this.mountPointService = null;
141         this.rpcProviderRegistry = null;
142         this.notificationPublishService = null;
143         this.clusterSingletonServiceProvider = null;
144         this.websocketmanagerService = null;
145         this.iEntityDataProvider = null;
146
147         this.webSocketService = null;
148     }
149
150     public void setDataBroker(DataBroker dataBroker) {
151         this.dataBroker = dataBroker;
152     }
153
154     public void setRpcProviderRegistry(RpcProviderService rpcProviderRegistry) {
155         this.rpcProviderRegistry = rpcProviderRegistry;
156     }
157
158     public void setNotificationPublishService(NotificationPublishService notificationPublishService) {
159         this.notificationPublishService = notificationPublishService;
160     }
161
162     public void setMountPointService(MountPointService mountPointService) {
163         this.mountPointService = mountPointService;
164     }
165     public void setClusterSingletonService(ClusterSingletonServiceProvider clusterSingletonService) {
166         this.clusterSingletonServiceProvider = clusterSingletonService;
167     }
168     public void setNetconfNodeStateService(NetconfNodeStateService netconfNodeStateService) {
169         this.netconfNodeStateService = netconfNodeStateService;
170     }
171     public void setWebsocketmanagerService(WebsocketmanagerService websocketmanagerService) {
172         this.websocketmanagerService = websocketmanagerService;
173     }
174     public void setEntityDataProvider(IEntityDataProvider iEntityDataProvider) {
175         this.iEntityDataProvider = iEntityDataProvider;
176     }
177
178     @SuppressWarnings({ "deprecation", "null" })
179     public void init() throws Exception {
180
181         LOG.info("Session Initiated start {}", APPLICATION_NAME);
182         this.iEntityDataProvider.setReadyStatus(false);
183
184         this.dataProvider = iEntityDataProvider.getDataProvider();        // Get configuration
185
186         ConfigurationFileRepresentation config = new ConfigurationFileRepresentation(CONFIGURATIONFILE);
187
188         this.notificationDelayService = new DevicemanagerNotificationDelayService(config);
189
190         //EsConfig dbConfig = new EsConfig(config);
191         //LOG.debug("esConfig=" + dbConfig.toString());
192         // Start database
193         // TODO Remove this database client
194         //this.htDatabaseClient = new HtDatabaseClient(dbConfig.getHosts());
195         //this.htDatabaseClient.waitForYellowStatus(DATABASE_TIMEOUT_MS);
196
197         // start service for device maintenance service
198         this.maintenanceService = new MaintenanceServiceImpl(iEntityDataProvider.getHtDatabaseMaintenance());
199
200         // Websockets
201         this.webSocketService = new WebSocketServiceClientImpl2(websocketmanagerService);
202
203         IEsConfig esConfig = iEntityDataProvider.getEsConfig();
204         // DCAE
205         this.dcaeProviderClient = new DcaeProviderClient(config, esConfig.getCluster(), this);
206
207         this.aaiProviderClient = new AaiProviderClient(config, this);
208         // EM
209         String myDbKeyNameExtended = MYDBKEYNAMEBASE + "-" + esConfig.getCluster();
210
211         this.aotsDcaeForwarder = new DcaeForwarderImpl(null, dcaeProviderClient, maintenanceService);
212
213         this.deviceManagerDatabaseAndNotificationService = new DeviceManagerDatabaseNotificationService(dataProvider, maintenanceService,webSocketService, notificationDelayService, aotsDcaeForwarder);
214
215         this.rpcPushNotificationsHandler = new RpcPushNotificationsHandler(webSocketService,
216                 dataProvider, aotsDcaeForwarder);
217         this.odlEventListenerHandler = new ODLEventListenerHandler(myDbKeyNameExtended, webSocketService,
218                 dataProvider, aotsDcaeForwarder);
219         this.archiveCleanService = new ArchiveCleanService(iEntityDataProvider.getEsConfig(), dataProvider);
220         this.housekeepingService = new ConnectionStatusHousekeepingService(this.dataBroker,
221                 dataProvider);
222         this.cssRegistration = this.clusterSingletonServiceProvider
223                 .registerClusterSingletonService(this.archiveCleanService);
224         this.cssRegistration2 = this.clusterSingletonServiceProvider
225                 .registerClusterSingletonService(this.housekeepingService);
226         // PM
227         this.performanceManager = new PerformanceManagerImpl(60, this, new MicrowaveHistoricalPerformanceWriterService(dataProvider), config);
228         // DM
229         // DeviceMonitor has to be available before netconfSubscriptionManager is
230         // configured
231         LOG.debug("start DeviceMonitor Service");
232         this.deviceMonitor = new DeviceMonitorImpl(dataBroker, odlEventListenerHandler, config);
233
234         // ResyncNetworkElementHouskeepingService
235         this.resyncNetworkElementHouskeepingService = new ResyncNetworkElementHouskeepingService(
236                 this, mountPointService, odlEventListenerHandler,
237                 dataProvider, deviceMonitor);
238
239         // RPC Service for specific services
240         // Start RPC Service
241         LOG.debug("start rpc service");
242         this.rpcApiService = new DeviceManagerApiServiceImpl(rpcProviderRegistry, maintenanceService,
243                 resyncNetworkElementHouskeepingService, rpcPushNotificationsHandler);
244
245         // netconfSubscriptionManager should be the last one because this is a callback
246         // service
247         LOG.debug("start NetconfSubscriptionManager Service");
248         // this.netconfSubscriptionManager = new
249         // NetconfSubscriptionManagerOfDeviceManager(this, dataBroker);
250         // this.netconfSubscriptionManager.register();
251
252         //---->>>>>>> OLD OLD OLD
253         //this.netconfChangeListener = new NetconfChangeListener(this, dataBroker);
254         //this.netconfChangeListener.register();
255
256         //---->>>>>>> NEW NEW NEW
257         this.forTest = new DeviceManagerNetconfConnectHandler(netconfNodeStateService, odlEventListenerHandler,
258                 deviceMonitor, this, factoryList);
259
260         writeToEventLog(APPLICATION_NAME, "startup", "done");
261         this.devicemanagerInitializationOk = true;
262
263         LOG.info("Session Initiated end. Initialization done {}", devicemanagerInitializationOk);
264         this.iEntityDataProvider.setReadyStatus(true);
265
266     }
267
268     @Override
269     public void close() {
270         LOG.info("DeviceManagerImpl closing ...");
271         close(performanceManager);
272         close(dcaeProviderClient);
273         close(aaiProviderClient);
274         close(deviceMonitor);
275         //close(htDatabaseClient);
276         //close(netconfChangeListener);
277         close(maintenanceService);
278         close(rpcApiService);
279         close(notificationDelayService);
280         close(archiveCleanService);
281         close(housekeepingService);
282         close(forTest);
283         close(cssRegistration, cssRegistration2);
284         LOG.info("DeviceManagerImpl closing done");
285     }
286
287     @Override
288     public @NonNull <L extends NetworkElementFactory> FactoryRegistration<L> registerNetworkElementFactory(@NonNull L factory) {
289         LOG.info("Factory registration {}", factory.getClass().getName());
290         MyNetworkElementFactory<L> myFactory = new MyNetworkElementFactory<>(factory, (a,b,c) -> initDefault(a,b,c));
291         factoryList.add(myFactory);
292         return new FactoryRegistration<L>() {
293
294             @Override
295             public @NonNull L getInstance() {
296                 return myFactory.getFactory();
297             }
298
299             @Override
300             public void close() {
301                 factoryList.remove(myFactory);
302             }
303
304         };
305     }
306
307     /**
308      * Execute register command, for network element
309      * @param mountPointNodeName  of new network element
310      * @param mountPoint of new network element
311      * @param inNe that needs to register
312      */
313     private void initDefault(String mountPointNodeName, MountPoint mountPoint, NetworkElement inNe) {
314         // sendUpdateNotification(mountPointNodeName, nNode.getConnectionStatus(), nNode);
315
316         NetworkElement result;
317         synchronized (networkelementLock) {
318             result = networkElementRepresentations.put(mountPointNodeName, inNe);
319         }
320         if (result != null) {
321             LOG.warn("NE list was not empty as expected, but contained {} ", result.getNodeId());
322         } else {
323             deviceMonitor.deviceConnectMasterIndication(mountPointNodeName, inNe);
324             inNe.register(); // Call NE specific initialization
325             odlEventListenerHandler.connectIndication(mountPointNodeName, inNe.getDeviceType());
326         }
327     }
328
329     @SuppressWarnings("null")
330     @Override
331     public @NonNull DataProvider getDataProvider() {
332         return this.dataProvider;
333     }
334
335     @SuppressWarnings("null")
336     @Override
337     public @NonNull NotificationService getNotificationService() {
338         return this.deviceManagerDatabaseAndNotificationService;
339     }
340
341     @SuppressWarnings("null")
342     @Override
343     public @NonNull FaultService getFaultService() {
344         return this.deviceManagerDatabaseAndNotificationService;
345     }
346
347     @SuppressWarnings("null")
348     @Override
349     public @NonNull EquipmentService getEquipmentService() {
350         return this.deviceManagerDatabaseAndNotificationService;
351     }
352
353     @SuppressWarnings("null")
354     @Override
355     public @NonNull AaiService getAaiService() {
356         return this.aaiProviderClient;
357     }
358
359     @SuppressWarnings("null")
360     @Override
361     public @NonNull MaintenanceService getMaintenanceService() {
362         return this.maintenanceService;
363     }
364
365     @SuppressWarnings("null")
366     @Override
367     public @NonNull PerformanceManager getPerformanceManagerService() {
368         return this.performanceManager;
369     }
370
371     @SuppressWarnings("null")
372     @Override
373     public @NonNull EventHandlingService getEventHandlingService() {
374         return this.odlEventListenerHandler;
375     }
376     // Deviceinitialization
377
378     /**
379      * Used to close all Services, that should support AutoCloseable Pattern
380      * @param toClose
381      */
382     private void close(AutoCloseable... toCloseList) {
383         for (AutoCloseable element : toCloseList) {
384             if (element != null) {
385                 try {
386                     element.close();
387                 } catch (Exception e) {
388                     LOG.warn("Problem during close {}", e);
389                 }
390             }
391         }
392     }
393
394     /*-------------------------------------------------------------------------------------------
395      * Functions
396      */
397
398     public ArchiveCleanService getArchiveCleanService() {
399         return this.archiveCleanService;
400     }
401
402     public DataProvider getDatabaseClientEvents() {
403         return dataProvider;
404     }
405
406     @Override
407     public DeviceManagerServiceProvider getServiceProvider() {
408         return this;
409     }
410
411     /**
412      * Indication if init() of devicemanager successfully done.
413      * @return true if init() was sucessfull. False if not done or not successfull.
414      */
415     public boolean isDevicemanagerInitializationOk() {
416         return this.devicemanagerInitializationOk;
417     }
418
419     /**
420      * Get NE object. Used by DCAE Service
421      * @param mountpoint mount point name
422      * @return null or NE specific data
423      */
424     public @Nullable NetworkElement getNeByMountpoint(String mountpoint) {
425
426         return networkElementRepresentations.get(mountpoint);
427
428     }
429
430     @Override
431     public void writeToEventLog(String objectId, String msg, String value) {
432         this.odlEventListenerHandler.writeEventLog(objectId, msg, value);
433     }
434
435 }