Removing blueprints-processor
[ccsdk/features.git] / sdnr / wt / devicemanager / provider / src / main / java / org / onap / ccsdk / features / sdnr / wt / devicemanager / base / onfcore / ONFCoreNetworkElement12Microwave.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.base.onfcore;
19
20 import java.io.PrintWriter;
21 import java.io.StringWriter;
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.Optional;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataProvider;
28 import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.AllPm;
29 import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.ONFLayerProtocolName;
30 import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc.OnfMicrowaveModel;
31 import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeForwarderInternal;
32 import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler.NetconfEventListenerHandler12;
33 import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime;
34 import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity;
35 import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.AttributeValueChangedNotificationXml;
36 import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml;
37 import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.WebSocketServiceClientInternal;
38 import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.types.EsHistoricalPerformance15Minutes;
39 import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.types.EsHistoricalPerformance24Hours;
40 import org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter.NotificationDelayService;
41 import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.Capabilities;
42 import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.INetconfAcessor;
43 import org.opendaylight.mdsal.binding.api.DataBroker;
44 import org.opendaylight.mdsal.binding.api.MountPoint;
45 import org.opendaylight.mdsal.binding.api.NotificationService;
46 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
47 import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.UniversalId;
48 import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.extension.g.Extension;
49 import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.logical.termination.point.g.Lp;
50 import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.GranularityPeriodType;
51 import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.OtnHistoryDataG;
52 import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.NetworkElementPac;
53 import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.network.element.pac.NetworkElementCurrentProblems;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementDeviceType;
55 import org.opendaylight.yangtools.concepts.ListenerRegistration;
56 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
57 import org.opendaylight.yangtools.yang.binding.NotificationListener;
58 import org.opendaylight.yangtools.yang.common.QName;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 /**
63  * Get information over NETCONF device according to ONF Coremodel. Read networkelement and
64  * conditional packages.
65  *
66  * Get conditional packages from Networkelement Possible interfaces are: MWPS, LTP(MWPS-TTP),
67  * MWAirInterfacePac, MicrowaveModel-ObjectClasses-AirInterface ETH-CTP,LTP(Client),
68  * MW_EthernetContainer_Pac MWS, LTP(MWS-CTP-xD), MWAirInterfaceDiversityPac,
69  * MicrowaveModel-ObjectClasses-AirInterfaceDiversity MWS, LTP(MWS-TTP),
70  * ,MicrowaveModel-ObjectClasses-HybridMwStructure MWS, LTP(MWS-TTP),
71  * ,MicrowaveModel-ObjectClasses-PureEthernetStructure
72  *
73  * @author herbert
74  *
75  */
76 public class ONFCoreNetworkElement12Microwave extends ONFCoreNetworkElement12Base
77         implements ONFCoreNetworkElementCallback, NotificationActor<AttributeValueChangedNotificationXml> {
78
79     private static final Logger LOG = LoggerFactory.getLogger(ONFCoreNetworkElement12Microwave.class);
80
81     /*-----------------------------------------------------------------------------
82      * Class members
83      */
84     private final @NonNull NetconfEventListenerHandler12 microwaveEventListener;
85     private final @NonNull OnfMicrowaveModel microwaveModel;
86     private final NotificationWorker<AttributeValueChangedNotificationXml> notificationQueue;
87
88     private ListenerRegistration<NotificationListener> listenerRegistrationresult = null;
89
90     /*-----------------------------------------------------------------------------
91      * Construction
92      */
93
94     /**
95      * Constructor
96      *
97      * @param mountPointNodeName as String
98      * @param capabilities of the specific network element
99      * @param netconfNodeDataBroker for the network element specific data
100      * @param webSocketService to forward event notifications
101      * @param databaseService to access the database
102      * @param dcaeProvider to forward problem / change notifications
103      */
104     ONFCoreNetworkElement12Microwave(INetconfAcessor acessor, String mountPointNodeName, Capabilities capabilities,
105             DataBroker netconfNodeDataBroker, WebSocketServiceClientInternal webSocketService,
106             DataProvider databaseService, DcaeForwarderInternal aotsDcaeForwarder,
107             NotificationDelayService<ProblemNotificationXml> notificationDelayService,
108             OnfMicrowaveModel onfMicrowaveModel) {
109
110         super(acessor, mountPointNodeName, netconfNodeDataBroker, capabilities);
111
112         this.microwaveModel = onfMicrowaveModel;
113         this.microwaveModel.setCoreData(this);
114
115         // Create MicrowaveService here
116         this.microwaveEventListener = new NetconfEventListenerHandler12(mountPointNodeName, webSocketService,
117                 databaseService, aotsDcaeForwarder, notificationDelayService, this);
118         this.microwaveModel.setOnfMicrowaveModelListener(microwaveEventListener);
119
120         this.notificationQueue = new NotificationWorker<>(1, 100, this);
121
122         // ->Below shifted to super class
123         // this.isNetworkElementCurrentProblemsSupporting12 =
124         // capabilities.isSupportingNamespaceAndRevision(NetworkElementPac.QNAME);
125         // LOG.debug("support necurrent-problem-list=" + this.isNetworkElementCurrentProblemsSupporting12);
126         // LOG.info("Create NE instance {}", InstanceList.QNAME.getLocalName());
127
128     }
129
130     /*-----------------------------------------------------------------------------
131      * Functions
132      */
133
134     /**
135      * DeviceMonitor Prepare check by updating NE state and reading all interfaces.
136      */
137     @Override
138     public void prepareCheck() {
139         synchronized (dmLock) {
140             boolean change = readNetworkElementAndInterfaces();
141             if (change) {
142                 int problems = microwaveEventListener.removeAllCurrentProblemsOfNode();
143                 List<ProblemNotificationXml> resultList = readAllCurrentProblemsOfNode();
144                 microwaveEventListener.initCurrentProblemStatus(resultList);
145                 LOG.info("Resync mountpoint {} for device {}. Removed {}. Current problems: {}", getMountPointNodeName(),
146                         getUuId(), problems, resultList.size());
147             }
148         }
149     }
150
151     // public boolean checkIfConnectionToMediatorIsOk() -> Shifted to super class
152     // public boolean checkIfConnectionToNeIsOk() -> Shifted to super class
153
154     /*-----------------------------------------------------------------------------
155      * Synchronization
156      */
157
158     // public void initSynchronizationExtension() -> Shifted to super class
159     // private InstanceList readPTPClockInstances() -> Shifted to super class
160
161     /*-----------------------------------------------------------------------------
162      * Services for NE/Device synchronization
163      */
164
165     /**
166      * Handling of specific Notifications from NE, indicating changes and need for synchronization.
167      *
168      * <attribute-value-changed-notification xmlns="urn:onf:params:xml:ns:yang:microwave-model">
169      * <attribute-name>/equipment-pac/equipment-current-problems</attribute-name>
170      * <object-id-ref>CARD-1.1.1.0</object-id-ref> <new-value></new-value>
171      * </attribute-value-changed-notification>
172      * <attribute-value-changed-notification xmlns="urn:onf:params:xml:ns:yang:microwave-model">
173      * <attribute-name>/network-element/extension[value-name="top-level-equipment"]/value</attribute-name>
174      * <object-id-ref>Hybrid-Z</object-id-ref>
175      * <new-value>SHELF-1.1.0.0,IDU-1.55.0.0,ODU-1.56.0.0,IDU-1.65.0.0</new-value>
176      * </attribute-value-changed-notification>
177      */
178
179
180     @Override
181     public void notificationFromNeListener(AttributeValueChangedNotificationXml notificationXml) {
182         notificationQueue.put(notificationXml);
183     }
184
185     @Override
186     public void notificationActor(AttributeValueChangedNotificationXml notificationXml) {
187
188         LOG.debug("Enter change notification listener");
189         if (LOG.isTraceEnabled()) {
190             LOG.trace("Notification: {}", notificationXml);
191         }
192         if (notificationXml.getAttributeName().equals("/equipment-pac/equipment-current-problems")) {
193             syncEquipmentPac(notificationXml.getObjectId());
194         } else if (notificationXml.getAttributeName()
195                 .equals("/network-element/extension[value-name=\"top-level-equipment\"]/value")) {
196             initialReadFromNetworkElement();
197         }
198         LOG.debug("Leave change notification listener");
199     }
200
201     /**
202      * Synchronize problems for a specific equipment-pac
203      *
204      * @param uuidString of the equipment-pac
205      */
206     private synchronized void syncEquipmentPac(String uuidString) {
207
208         int problems = microwaveEventListener.removeObjectsCurrentProblemsOfNode(uuidString);
209         LOG.debug("Removed {} problems for uuid {}", problems, uuidString);
210
211         List<ProblemNotificationXml> resultList = equipment.addProblemsofNodeObject(uuidString);
212         microwaveEventListener.initCurrentProblemStatus(resultList);
213         LOG.debug("Added {} problems for uuid {}", resultList.size(), uuidString);
214
215     }
216
217
218     /*-----------------------------------------------------------------------------
219      * Problem/Fault related functions
220      */
221
222     /**
223      * Read during startup all relevant structure and status parameters from device
224      */
225     @Override
226     public synchronized void initialReadFromNetworkElement() {
227         // optionalNe.getLtp().get(0).getLp();
228         LOG.debug("Get info about {}", getMountPointNodeName());
229
230         int problems = microwaveEventListener.removeAllCurrentProblemsOfNode();
231         LOG.debug("Removed all {} problems from database at registration", problems);
232
233         // Step 2.1: access data broker within this mount point
234         LOG.debug("DBRead start");
235
236         // Step 2.2: read ne from data store
237         readNetworkElementAndInterfaces();
238         equipment.readNetworkElementEquipment();
239
240         // Step 2.3: read the existing faults and add to DB
241         List<ProblemNotificationXml> resultList = readAllCurrentProblemsOfNode();
242         equipment.addProblemsofNode(resultList);
243
244         microwaveEventListener.initCurrentProblemStatus(resultList);
245
246         microwaveEventListener.writeEquipment(equipment);
247
248         LOG.info("Found info at {} for device {} number of problems: {}", getMountPointNodeName(), getUuId(),
249                 resultList.size());
250     }
251
252     /**
253      * LOG the newly added problems of the interface pac
254      *
255      * @param idxStart
256      * @param uuid
257      * @param resultList
258      */
259     private void debugResultList(String uuid, List<ProblemNotificationXml> resultList, int idxStart) {
260         if (LOG.isDebugEnabled()) {
261             StringBuffer sb = new StringBuffer();
262             int idx = 0;
263             for (int t = idxStart; t < resultList.size(); t++) {
264                 sb.append(idx++);
265                 sb.append(":{");
266                 sb.append(resultList.get(t));
267                 sb.append('}');
268             }
269             LOG.debug("Found problems {} {}", uuid, sb.toString());
270         }
271     }
272
273     /**
274      * Read current problems of AirInterfaces and EthernetContainer according to NE status into DB
275      *
276      * @return List with all problems
277      */
278     @Override
279     protected List<ProblemNotificationXml> readAllCurrentProblemsOfNode() {
280
281         // Step 2.3: read the existing faults and add to DB
282         List<ProblemNotificationXml> resultList = new ArrayList<>();
283         int idxStart; // Start index for debug messages
284         UniversalId uuid;
285
286         synchronized (getPmLock()) {
287             for (Lp lp : getInterfaceList()) {
288
289                 idxStart = resultList.size();
290                 uuid = lp.getUuid();
291                 Class<?> lpClass = getLpExtension(lp);
292
293                 ONFLayerProtocolName lpName = ONFLayerProtocolName.valueOf(lp.getLayerProtocolName());
294
295                 microwaveModel.readTheFaultsOfMicrowaveModel(lpName, lpClass, uuid, resultList);
296
297                 debugResultList(uuid.getValue(), resultList, idxStart);
298
299             }
300         }
301
302         // Step 2.4: Read other problems from mountpoint
303         if (isNetworkElementCurrentProblemsSupporting12) {
304             idxStart = resultList.size();
305             readNetworkElementCurrentProblems12(resultList);
306             debugResultList("CurrentProblems12", resultList, idxStart);
307         }
308
309         return resultList;
310
311     }
312
313     /**
314      * Get from LayerProtocolExtensions the related generated ONF Interface PAC class which represents it.
315      *
316      * @param lp logical termination point
317      * @return Class of InterfacePac
318      */
319     @Nullable
320     private Class<?> getLpExtension(@Nullable Lp lp) {
321
322         String capability = EMPTY;
323         String revision = EMPTY;
324         String conditionalPackage = EMPTY;
325         Class<?> res = null;
326
327         if (lp != null) {
328             for (Extension e : getExtensionList(lp)) {
329                 if (e.getValueName().contentEquals("capability")) {
330                     capability = e.getValue();
331                     int idx = capability.indexOf("?");
332                     if (idx != -1) {
333                         capability = capability.substring(0, idx);
334                     }
335                 }
336                 if (e.getValueName().contentEquals("revision")) {
337                     revision = e.getValue();
338                 }
339                 if (e.getValueName().contentEquals("conditional-package")) {
340                     conditionalPackage = e.getValue();
341                 }
342             }
343         }
344         // QName qName =
345         // org.opendaylight.yangtools.yang.common.QName.create("urn:onf:params:xml:ns:yang:microwave-model",
346         // "2017-03-24", "mw-air-interface-pac").intern();
347         LOG.info("LpExtension capability={} revision={} conditionalPackage={}", capability, revision,
348                 conditionalPackage);
349         if (!capability.isEmpty() && !revision.isEmpty() && !conditionalPackage.isEmpty()) {
350             try {
351                 QName qName = QName.create(capability, revision, conditionalPackage);
352                 res = this.microwaveModel.getClassForLtpExtension(qName);
353             } catch (IllegalArgumentException e) {
354                 LOG.debug("Can not create QName from ({}{}{}): {}", capability, revision, conditionalPackage,
355                         e.getMessage());
356             }
357         }
358         return res;
359     }
360
361     /**
362      * Read element from class that could be not available
363      *
364      * @param ltp layer termination point
365      * @return List with extension parameters or empty list
366      */
367     @NonNull
368     private static List<Extension> getExtensionList(@Nullable Lp ltp) {
369         if (ltp != null && ltp.getExtension() != null) {
370             return ltp.getExtension();
371         } else {
372             return EMPTYLTPEXTENSIONLIST;
373         }
374     }
375
376     @NonNull
377     private List<? extends OtnHistoryDataG> readTheHistoricalPerformanceData(Lp lp) {
378         ONFLayerProtocolName lpName = ONFLayerProtocolName.valueOf(lp.getLayerProtocolName());
379
380         return this.microwaveModel.readTheHistoricalPerformanceData(lpName, lp);
381     }
382
383     @Override
384     public AllPm getHistoricalPM() {
385
386         synchronized (getPmLock()) {
387             if (pmLp != null) {
388                 LOG.debug("Enter query PM");
389                 AllPm allPm = new AllPm();
390                 Lp lp = pmLp;
391
392                 List<? extends OtnHistoryDataG> resultList = readTheHistoricalPerformanceData(lp);
393                 LOG.debug("Got records: {}", resultList.size());
394                 // org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.GranularityPeriodType
395                 GranularityPeriodType granularityPeriod;
396                 for (OtnHistoryDataG perf : resultList) {
397
398                     granularityPeriod = perf.getGranularityPeriod();
399                     if (granularityPeriod == null) {
400                         granularityPeriod = GranularityPeriodType.Unknown;
401                     }
402
403                     switch (granularityPeriod) {
404                         case Period15Min: {
405                             EsHistoricalPerformance15Minutes pm =
406                                     new EsHistoricalPerformance15Minutes(getMountPointNodeName(), lp)
407                                             .setHistoricalRecord15Minutes(perf);
408                             allPm.add(pm);
409                         }
410                             break;
411
412                         case Period24Hours: {
413                             EsHistoricalPerformance24Hours pm =
414                                     new EsHistoricalPerformance24Hours(getMountPointNodeName(), lp)
415                                             .setHistoricalRecord24Hours(perf);
416                             LOG.debug("Write 24h write to DB");
417                             allPm.add(pm);
418                         }
419                             break;
420
421                         default:
422                             LOG.warn("Unknown granularity {}", perf.getGranularityPeriod());
423                             break;
424
425                     }
426                 }
427                 LOG.debug("Deliver normalized records: {}", allPm.size());
428                 return allPm;
429             } else {
430                 LOG.debug("Deliver empty, no LTP");
431                 return AllPm.getEmpty();
432             }
433         }
434     }
435
436
437     /**
438      * Remove all entries from list
439      */
440     @Override
441     public int removeAllCurrentProblemsOfNode() {
442         return microwaveEventListener.removeAllCurrentProblemsOfNode();
443     }
444
445     /**
446      * Register the listener
447      */
448     @Override
449     public void doRegisterEventListener(MountPoint mountPoint) {
450         LOG.info("End registration listener for Mountpoint {}", mountPoint.getIdentifier().toString());
451         final Optional<NotificationService> optionalNotificationService =
452                 mountPoint.getService(NotificationService.class);
453         final NotificationService notificationService = optionalNotificationService.get();
454         // notificationService.registerNotificationListener(microwaveEventListener);
455         listenerRegistrationresult =
456                 notificationService.registerNotificationListener(microwaveModel.getNotificationListener());
457         LOG.info("End registration listener for Mountpoint {} Listener: {} Result: {}",
458                 mountPoint.getIdentifier().toString(), optionalNotificationService, listenerRegistrationresult);
459     }
460
461     /*------------------------------------------------------------
462      * private function to access database
463      */
464
465     /*-----------------------------------------------------------------------------
466      * Reading problems for the networkElement V1.2
467      */
468
469     private List<ProblemNotificationXml> readNetworkElementCurrentProblems12(List<ProblemNotificationXml> resultList) {
470
471         LOG.info("DBRead Get {} NetworkElementCurrentProblems12", getMountPointNodeName());
472
473         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.NetworkElementPac> networkElementCurrentProblemsIID =
474                 InstanceIdentifier.builder(
475                         org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.NetworkElementPac.class)
476                         .build();
477
478         // Step 2.3: read to the config data store
479         NetworkElementPac problemPac;
480         NetworkElementCurrentProblems problems;
481         try {
482             problemPac = getGenericTransactionUtils().readData(getNetconfNodeDataBroker(), LogicalDatastoreType.OPERATIONAL,
483                     networkElementCurrentProblemsIID);
484             problems = problemPac.getNetworkElementCurrentProblems();
485             if (problems == null) {
486                 LOG.debug("DBRead no NetworkElementCurrentProblems12");
487             } else {
488                 for (org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.network.element.current.problems.g.CurrentProblemList problem : problems.nonnullCurrentProblemList()) {
489                     resultList.add(new ProblemNotificationXml(getMountPointNodeName(), problem.getObjectReference(),
490                             problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()),
491                             problem.getSequenceNumber(),
492                             InternalDateAndTime.valueOf(problem.getTimeStamp())));
493                 }
494             }
495         } catch (Exception e) {
496             StringWriter sw = new StringWriter();
497             PrintWriter pw = new PrintWriter(sw);
498             e.printStackTrace(pw);
499             LOG.warn("DBRead {} NetworkElementCurrentProblems12 not supported. Message '{}' ", getMountPointNodeName(), pw.toString());
500         }
501         return resultList;
502
503     }
504
505     @Override
506     public void close() throws Exception {
507         if (listenerRegistrationresult != null) {
508             listenerRegistrationresult.close();
509         }
510     }
511
512     @Override
513     public NetworkElementDeviceType getDeviceType() {
514         return NetworkElementDeviceType.Wireless;
515     }
516 }