8367a87d3f25d166281378dbbc922cb318eb9668
[ccsdk/features.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
7  * ================================================================================
8  * Update Copyright (C) 2021 Samsung Electronics Intellectual Property. All rights reserved.
9  * =================================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  *     http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END=========================================================
22  *
23  */
24 package org.onap.ccsdk.features.sdnr.wt.dataprovider.database.elasticsearch.data.entity;
25
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Date;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Optional;
33 import javax.annotation.Nonnull;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient;
37 import org.onap.ccsdk.features.sdnr.wt.common.database.queries.BoolQueryBuilder;
38 import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilder;
39 import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilders;
40 import org.onap.ccsdk.features.sdnr.wt.common.database.queries.RangeQueryBuilder;
41 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.elasticsearch.EsDataObjectReaderWriter2;
42 import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.ArchiveCleanProvider;
43 import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataInconsistencyException;
44 import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataProvider;
45 import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.NetconfTimeStamp;
46 import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.types.NetconfTimeStampImpl;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.CmlogBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.CmlogEntity;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.ConnectionLogStatus;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.ConnectionlogBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.ConnectionlogEntity;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.Entity;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.EventlogBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.EventlogEntity;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.FaultcurrentBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.FaultcurrentEntity;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.FaultlogBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.FaultlogEntity;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.GranularityPeriodType;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.Guicutthrough;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.GuicutthroughBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.GuicutthroughEntity;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.Inventory;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.InventoryBuilder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.InventoryEntity;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.NetworkElementConnectionBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.NetworkElementConnectionEntity;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.PmdataEntity;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.PmdataEntityBuilder;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.UpdateNetworkElementConnectionInputBuilder;
72 import org.opendaylight.yangtools.yang.common.Uint32;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75
76 /**
77  * Event service, writing all events into the database into the appropriate index.
78  *
79  * @author herbert
80  */
81 public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvider {
82     private static final Logger LOG = LoggerFactory.getLogger(HtDatabaseEventsService.class);
83
84     private static final NetconfTimeStamp NETCONFTIME_CONVERTER = NetconfTimeStampImpl.getConverter();
85
86     private static final int ROOT_TREE_LEVEL = 0;
87
88     private HtDatabaseClient client;
89     private EsDataObjectReaderWriter2<EventlogEntity> eventRWEventLogDevicemanager;
90     private EsDataObjectReaderWriter2<InventoryEntity> eventRWEquipment;
91     private EsDataObjectReaderWriter2<FaultcurrentEntity> eventRWFaultCurrentDB;
92     private EsDataObjectReaderWriter2<FaultlogEntity> eventRWFaultLogDB;
93     private EsDataObjectReaderWriter2<CmlogEntity> eventRWFCMLogDB;
94     private EsDataObjectReaderWriter2<ConnectionlogEntity> eventRWConnectionLogDB;
95     private final EsDataObjectReaderWriter2<NetworkElementConnectionEntity> networkelementConnectionDB;
96     private final EsDataObjectReaderWriter2<GuicutthroughEntity> guiCutThroughDB;
97     private final EsDataObjectReaderWriter2<PmdataEntity> pmData15mDB;
98     private final EsDataObjectReaderWriter2<PmdataEntity> pmData24hDB;
99     // --- Construct and initialize
100
101     public HtDatabaseEventsService(HtDatabaseClient client) throws Exception {
102
103         LOG.info("Create {} start", HtDatabaseEventsService.class);
104
105         try {
106             // Create control structure
107             this.client = client;
108
109             eventRWEventLogDevicemanager = new EsDataObjectReaderWriter2<>(client, Entity.Eventlog,
110                     EventlogEntity.class, EventlogBuilder.class);
111
112             eventRWEquipment = new EsDataObjectReaderWriter2<>(client, Entity.Inventoryequipment, InventoryEntity.class,
113                     InventoryBuilder.class);
114
115             eventRWFaultCurrentDB = new EsDataObjectReaderWriter2<>(client, Entity.Faultcurrent,
116                     FaultcurrentEntity.class, FaultcurrentBuilder.class);
117
118             eventRWFaultLogDB = new EsDataObjectReaderWriter2<>(client, Entity.Faultlog, FaultlogEntity.class,
119                     FaultlogBuilder.class);
120
121             eventRWFCMLogDB =
122                     new EsDataObjectReaderWriter2<>(client, Entity.Cmlog, CmlogEntity.class, CmlogBuilder.class);
123
124             eventRWConnectionLogDB = new EsDataObjectReaderWriter2<>(client, Entity.Connectionlog,
125                     ConnectionlogEntity.class, ConnectionlogBuilder.class);
126
127             networkelementConnectionDB = new EsDataObjectReaderWriter2<>(client, Entity.NetworkelementConnection,
128                     NetworkElementConnectionEntity.class, NetworkElementConnectionBuilder.class, true)
129                             .setEsIdAttributeName("_id");
130
131             guiCutThroughDB = new EsDataObjectReaderWriter2<>(client, Entity.Guicutthrough, GuicutthroughEntity.class,
132                     GuicutthroughBuilder.class);
133
134             pmData15mDB = new EsDataObjectReaderWriter2<>(client, Entity.Historicalperformance15min, PmdataEntity.class,
135                     PmdataEntityBuilder.class);
136
137             pmData24hDB = new EsDataObjectReaderWriter2<>(client, Entity.Historicalperformance24h, PmdataEntity.class,
138                     PmdataEntityBuilder.class);
139
140         } catch (Exception e) {
141             LOG.error("Can not start database client. Exception: {}", e);
142             throw new Exception("Can not start database client. Exception: {}", e);
143         }
144         LOG.info("Create {} finished. DB Service {} started.", HtDatabaseEventsService.class,
145                 client != null ? "sucessfully" : "not");
146     }
147
148     // --- Function
149
150     // -- Connection log
151     @Override
152     public void writeConnectionLog(ConnectionlogEntity event) {
153         if (assertIfClientNull(event)) {
154             return;
155         }
156         LOG.debug("Write event: {}", event);
157         eventRWConnectionLogDB.write(event, null);
158
159     }
160
161     // -- Event log
162     @Override
163     public void writeEventLog(EventlogEntity event) {
164         if (assertIfClientNull("No client to write {}", event)) {
165             return;
166         }
167
168         LOG.debug("Write event: {}", event.toString());
169         eventRWEventLogDevicemanager.write(event, null);
170     }
171
172     // -- Fault log
173
174     @Override
175     public void writeFaultLog(FaultlogEntity fault) {
176         if (assertIfClientNull(fault)) {
177             return;
178         }
179
180         LOG.debug("Write fault to faultlog: {}", fault.toString());
181         eventRWFaultLogDB.write(fault, null);
182     }
183
184     //-- CM log
185
186     @Override
187     public void writeCMLog(CmlogEntity cm) {
188         if (assertIfClientNull(cm)) {
189             return;
190         }
191
192         LOG.debug("Write CM to cmlog: {}", cm.toString());
193         eventRWFCMLogDB.write(cm, null);
194     }
195
196     // -- Fault current
197
198     @Override
199     public void updateFaultCurrent(FaultcurrentEntity fault) {
200         if (assertIfClientNull(fault)) {
201             return;
202         }
203
204         if (FaultEntityManager.isManagedAsCurrentProblem(fault)) {
205             if (FaultEntityManager.isNoAlarmIndication(fault)) {
206                 LOG.debug("Remove from currentFaults: {}", fault.toString());
207                 eventRWFaultCurrentDB.remove(FaultEntityManager.genSpecificEsId(fault));
208             } else {
209                 LOG.debug("Write to currentFaults: {}", fault.toString());
210                 eventRWFaultCurrentDB.write(fault, FaultEntityManager.genSpecificEsId(fault));
211             }
212         } else {
213             LOG.debug("Ingnore for currentFaults: {}", fault.toString());
214         }
215     }
216
217     /**
218      * Remove all entries for one node
219      *
220      * @param nodeName contains the mountpointname
221      * @return number of deleted entries
222      */
223     @Override
224     public int clearFaultsCurrentOfNode(String nodeName) {
225         if (assertIfClientNullForNodeName(nodeName)) {
226             return -1;
227         }
228
229         LOG.debug("Remove from currentFaults all faults for node: {}", nodeName);
230         return eventRWFaultCurrentDB.remove(EsFaultCurrent.getQueryForOneNode(nodeName));
231     }
232
233     /**
234      * Remove all entries for one node
235      *
236      * @param nodeName contains the mountpointname
237      * @param objectId of element to be deleted
238      * @return number of deleted entries
239      */
240     @Override
241     public int clearFaultsCurrentOfNodeWithObjectId(String nodeName, String objectId) {
242         if (assertIfClientNullForNodeName(nodeName)) {
243             return -1;
244         }
245
246         LOG.debug("Remove from currentFaults all faults for node/objectId: {}/{}", nodeName, objectId);
247         return eventRWFaultCurrentDB.remove(EsFaultCurrent.getQueryForOneNodeAndObjectId(nodeName, objectId));
248     }
249
250     /**
251      * Deliver list with all mountpoint/node-names in the database.
252      *
253      * @return List of all mountpoint/node-names the had active alarms.
254      */
255     @Override
256     public @Nonnull List<String> getAllNodesWithCurrentAlarms() {
257         if (assertIfClientNull("No DB, can not delete for all nodes", null)) {
258             return new ArrayList<>();
259         }
260
261         LOG.debug("Remove from currentFaults faults for all node");
262         List<String> nodeNames = new ArrayList<>();
263
264         for (FaultcurrentEntity fault : eventRWFaultCurrentDB.doReadAll().getHits()) {
265             String nodeName = fault.getNodeId();
266             if (!nodeNames.contains(nodeName)) {
267                 // this.clearFaultsCurrentOfNode(nodeName); -> Function shifted
268                 nodeNames.add(nodeName);
269             }
270         }
271         return nodeNames;
272     }
273
274     // -- Inventory and equipment current
275
276     /**
277      * write internal equipment to database
278      *
279      * @param internalEquipment with mandatory fields.
280      */
281
282     private void writeInventory(Inventory internalEquipment) {
283
284         if (internalEquipment.getManufacturerIdentifier() == null) {
285             internalEquipment = new InventoryBuilder(internalEquipment).setManufacturerIdentifier("").build();
286         }
287         if (internalEquipment.getDate() == null) {
288             internalEquipment = new InventoryBuilder(internalEquipment).setDate("").build();
289         }
290         eventRWEquipment.write(internalEquipment, internalEquipment.getNodeId() + "/" + internalEquipment.getUuid());
291     }
292
293     /**
294      * write internal equipment to database
295      *
296      * @param nodeId
297      * @param list
298      */
299     @Override
300     public void writeInventory(String nodeId, List<Inventory> list) {
301
302         try {
303             checkConsistency(nodeId, list);
304         } catch (DataInconsistencyException e) {
305             LOG.warn("inventory list for node {} is not consistent", nodeId, e);
306             list = e.getRepairedList();
307         }
308
309         for (Inventory internalEquipment : list) {
310             this.writeInventory(internalEquipment);
311         }
312     }
313
314     private static void checkConsistency(String nodeId, List<Inventory> list) throws DataInconsistencyException {
315         final String UNBOUND_INVENTORY_UUID = "unbound";
316         List<String> failures = new ArrayList<>();
317         long treeLevel;
318         int failCounter = 0;
319         Map<String, Inventory> repairList = new HashMap<>();
320         InventoryBuilder repairedItem;
321         InventoryBuilder unboundItem = new InventoryBuilder().setNodeId(nodeId).setUuid(UNBOUND_INVENTORY_UUID)
322                 .setTreeLevel(Uint32.valueOf(0));;
323         for (Inventory item : list) {
324             repairedItem = new InventoryBuilder(item);
325             // check for bad node-id
326             if (!nodeId.equals(item.getNodeId())) {
327                 failures.add(String.format("missing node-id for equipment(uuid=%s)", item.getUuid()));
328                 repairedItem.setNodeId(nodeId);
329                 failCounter++;
330             }
331             // check missing tree-level
332             if (item.getTreeLevel() == null) {
333                 failures.add(String.format("missing tree-level for equipment(uuid=%s)", item.getUuid()));
334                 repairedItem.setTreeLevel(Uint32.valueOf(ROOT_TREE_LEVEL));
335                 failCounter++;
336
337             } else {
338                 treeLevel = item.getTreeLevel().longValue();
339                 if (treeLevel > ROOT_TREE_LEVEL) {
340                     // check non root elem and missing parent
341                     if (item.getParentUuid() == null) {
342                         failures.add(String.format("Non root level element (uuid=%s) has to have a parent element",
343                                 item.getUuid()));
344                         failCounter++;
345                         repairedItem.setParentUuid(UNBOUND_INVENTORY_UUID);
346                         repairList.put(unboundItem.getUuid(), unboundItem.build());
347                     }
348                     // check that parent exists in list and is tree-level -1
349                     else {
350                         Optional<Inventory> parent =
351                                 list.stream().filter(e -> item.getParentUuid().equals(e.getUuid())).findFirst();
352                         if (parent.isEmpty()) {
353                             failures.add(String.format("no parent found for uuid=%s with parent-uuid=%s",
354                                     item.getUuid(), item.getParentUuid()));
355                             repairedItem.setParentUuid(UNBOUND_INVENTORY_UUID);
356                             failCounter++;
357                         }
358                     }
359                 }
360                 // check for duplicated uui
361                 Optional<Inventory> duplicate = list
362                         .stream().filter(e -> !item.equals(e) && item.getUuid() != null
363                                 && item.getUuid().equals(e.getUuid()) && repairList.containsKey(e.getUuid()))
364                         .findFirst();
365                 if (duplicate.isPresent()) {
366                     failures.add(String.format("found duplicate uuid=%s", item.getUuid()));
367                     failCounter++;
368                     continue;
369
370                 }
371                 if (failCounter > 0) {
372                     repairList.put(repairedItem.getUuid(), repairedItem.build());
373                 } else {
374                     repairList.put(item.getUuid(), item);
375                 }
376             }
377         }
378
379         if (failures.size() > 0) {
380             throw new DataInconsistencyException(new ArrayList<>(repairList.values()),
381                     "inventory list is not consistent;\n" + String.join("\n", failures));
382         }
383     }
384
385     // -- Networkelement
386
387     /**
388      * join base with parameters of toJoin (only non null values)
389      *
390      * @param base base object
391      * @param toJoin object with new property values
392      * @return new joined object
393      */
394     @SuppressWarnings("unused")
395     private NetworkElementConnectionEntity joinNe(NetworkElementConnectionEntity base,
396             NetworkElementConnectionEntity toJoin) {
397         if (base == null) {
398             return toJoin;
399         }
400         NetworkElementConnectionBuilder builder = new NetworkElementConnectionBuilder(base);
401         if (toJoin != null) {
402             if (toJoin.requireIsRequired() != null) {
403                 builder.setIsRequired(toJoin.requireIsRequired());
404             }
405             if (toJoin.getCoreModelCapability() != null) {
406                 builder.setCoreModelCapability(toJoin.getCoreModelCapability());
407             }
408             if (toJoin.getDeviceType() != null) {
409                 builder.setDeviceType(toJoin.getDeviceType());
410             }
411             if (toJoin.getHost() != null) {
412                 builder.setHost(toJoin.getHost());
413             }
414             if (toJoin.getNodeDetails() != null) {
415                 builder.setNodeDetails(toJoin.getNodeDetails());
416             }
417             if (toJoin.getPassword() != null) {
418                 builder.setPassword(toJoin.getPassword());
419             }
420             if (toJoin.getPort() != null) {
421                 builder.setPort(toJoin.getPort());
422             }
423             if (toJoin.getStatus() != null) {
424                 builder.setStatus(toJoin.getStatus());
425             }
426             if (toJoin.getUsername() != null) {
427                 builder.setUsername(toJoin.getUsername());
428             }
429         }
430         return builder.build();
431     }
432
433     /**
434      *
435      * @param networkElementConnectionEntitiy to wirte to DB
436      * @param nodeId Id for this DB element
437      */
438     @Override
439     public boolean updateNetworkConnectionDeviceType(NetworkElementConnectionEntity networkElementConnectionEntitiy,
440             String nodeId) {
441         return this.networkelementConnectionDB.update(networkElementConnectionEntitiy, nodeId) != null;
442         // NetworkElementConnectionEntity e =
443         // this.networkelementConnectionDB.read(nodeId);
444         // this.networkelementConnectionDB.write(this.joinNe(e,
445         // networkElementConnectionEntitiy), nodeId);
446     }
447
448     /**
449      * Update after new mountpoint registration
450      *
451      * @param networkElementConnectionEntitiy data
452      * @param nodeId of device (mountpoint name)
453      */
454     @Override
455     public boolean updateNetworkConnection22(NetworkElementConnectionEntity networkElementConnectionEntitiy,
456             String nodeId) {
457         LOG.debug("update networkelement-connection for {} with data {}", nodeId, networkElementConnectionEntitiy);
458         return this.networkelementConnectionDB.updateOrCreate(networkElementConnectionEntitiy, nodeId,
459                 Arrays.asList("is-required", "username", "password")) != null;
460         // NetworkElementConnectionEntity e =
461         // this.networkelementConnectionDB.read(nodeId);
462         // this.networkelementConnectionDB.write(this.joinNe(e,
463         // networkElementConnectionEntitiy), nodeId);
464
465     }
466
467     /* please do not remove */
468     // public void cleanNetworkElementConnections() {
469     // this.networkelementConnectionDB.remove(QueryBuilders.matchQuery("is-required",
470     // false));
471     // CreateNetworkElementConnectionInput x = new
472     // CreateNetworkElementConnectionInputBuilder().setStatus(ConnectionLogStatus.Disconnected).build();
473     // this.networkelementConnectionDB.update(x,QueryBuilders.matchAllQuery());
474     // }
475
476     @Override
477     public void removeNetworkConnection(String nodeId) {
478         Boolean isRequired;
479         NetworkElementConnectionEntity e = this.networkelementConnectionDB.read(nodeId);
480         if (e != null && (isRequired = e.requireIsRequired()) != null) {
481             if (isRequired) {
482                 LOG.debug("updating connection status for {} of required ne to disconnected", nodeId);
483                 this.networkelementConnectionDB.update(new UpdateNetworkElementConnectionInputBuilder()
484                         .setStatus(ConnectionLogStatus.Disconnected).build(), nodeId);
485             } else {
486                 LOG.debug("remove networkelement-connection for {} entry because of non-required", nodeId);
487                 this.networkelementConnectionDB.remove(nodeId);
488             }
489         } else {
490             LOG.warn("Unable to update connection-status. dbentry for {} not found in networkelement-connection",
491                     nodeId);
492         }
493     }
494
495     // -- Multiple areas
496
497     @Override
498     public int doIndexClean(Date olderAreOutdated) {
499
500         String netconfTimeStamp = NETCONFTIME_CONVERTER.getTimeStampAsNetconfString(olderAreOutdated);
501         int removed = 0;
502
503         QueryBuilder queryEventBase = EsEventBase.getQueryForTimeStamp(netconfTimeStamp);
504         removed += eventRWEventLogDevicemanager.remove(queryEventBase);
505
506         QueryBuilder queryFaultLog = EsFaultLogDevicemanager.getQueryForTimeStamp(netconfTimeStamp);
507         removed += eventRWFaultLogDB.remove(queryFaultLog);
508
509         QueryBuilder queryCMLog = EsCMLogDevicemanager.getQueryForTimeStamp(netconfTimeStamp);
510         removed += eventRWFCMLogDB.remove(queryCMLog);
511
512         return removed;
513     }
514
515     @Override
516     public long getNumberOfOldObjects(Date olderAreOutdated) {
517
518         String netconfTimeStamp = NETCONFTIME_CONVERTER.getTimeStampAsNetconfString(olderAreOutdated);
519         int numberOfElements = 0;
520
521         QueryBuilder queryEventBase = EsEventBase.getQueryForTimeStamp(netconfTimeStamp);
522         numberOfElements += eventRWEventLogDevicemanager.doReadAll(queryEventBase).getTotal();
523
524         QueryBuilder queryFaultLog = EsFaultLogDevicemanager.getQueryForTimeStamp(netconfTimeStamp);
525         numberOfElements += eventRWFaultLogDB.doReadAll(queryFaultLog).getTotal();
526
527         QueryBuilder queryCMLog = EsCMLogDevicemanager.getQueryForTimeStamp(netconfTimeStamp);
528         numberOfElements += eventRWFCMLogDB.doReadAll(queryCMLog).getTotal();
529
530         return numberOfElements;
531     }
532
533     // -- Helper
534
535     /**
536      * Verify status of client
537      *
538      * @param event that is printed with message
539      * @return true if client is null
540      */
541     private boolean assertIfClientNull(Object event) {
542         return assertIfClientNull("No DB, can not write: {}", event);
543     }
544
545     private boolean assertIfClientNullForNodeName(Object object) {
546         return assertIfClientNull("No DB, can not handle node: {}", object);
547     }
548
549     /**
550      * Verify status of client
551      *
552      * @param message to print including {} for object printout.
553      * @return true if client is null
554      */
555     private boolean assertIfClientNull(String message, Object object) {
556         if (client == null) {
557             LOG.debug(message, object);
558             return true;
559         }
560         return false;
561     }
562
563     // ### sub classes
564
565     private static class EsEventBase {
566         /**
567          * Query to get older Elements
568          *
569          * @param netconfTimeStamp to identify older Elements
570          * @return QueryBuilder for older elements related to timestamp
571          */
572         private static QueryBuilder getQueryForTimeStamp(String netconfTimeStamp) {
573             return new RangeQueryBuilder("timestamp").lte(netconfTimeStamp);
574         }
575     }
576
577     private static class EsFaultLogDevicemanager {
578         /**
579          * Get older Elements
580          *
581          * @param netconfTimeStamp to identify query elements older than this timestamp.
582          * @return QueryBuilder for related elements
583          */
584         public static QueryBuilder getQueryForTimeStamp(String netconfTimeStamp) {
585             return new RangeQueryBuilder("timestamp").lte(netconfTimeStamp);
586         }
587     }
588
589     private static class EsCMLogDevicemanager {
590         /**
591          * Get older Elements
592          *
593          * @param netconfTimeStamp to identify query elements older than this timestamp.
594          * @return QueryBuilder for related elements
595          */
596         public static QueryBuilder getQueryForTimeStamp(String netconfTimeStamp) {
597             return new RangeQueryBuilder("timestamp").lte(netconfTimeStamp);
598         }
599     }
600
601     public static class EsFaultCurrent {
602         /**
603          * @param nodeName name of the node
604          * @return query builder
605          */
606         public static QueryBuilder getQueryForOneNode(String nodeName) {
607             return QueryBuilders.matchQuery("node-id", nodeName);
608         }
609
610         public static QueryBuilder getQueryForOneNodeAndObjectId(String nodeName, String objectId) {
611             BoolQueryBuilder bq = QueryBuilders.boolQuery();
612             bq.must(QueryBuilders.matchQuery("node-id", nodeName));
613             bq.must(QueryBuilders.matchQuery("object-id", objectId));
614             return bq;
615         }
616     }
617
618     @Override
619     public List<NetworkElementConnectionEntity> getNetworkElementConnections() {
620         return this.networkelementConnectionDB.doReadAll().getHits();
621     }
622
623     @Override
624     public void doWritePerformanceData(List<PmdataEntity> list) {
625
626         list.forEach(elem -> {
627             GranularityPeriodType granularityPeriod = nnGetGranularityPeriodType(elem.getGranularityPeriod());
628             // _id": "Sim12600/LP-MWPS-TTP-01/2017-07-04T15:15:00.0+00:00"
629             StringBuffer id = new StringBuffer();
630             DateAndTime date = elem.getTimeStamp();
631             id.append(elem.getNodeName());
632             id.append("/");
633             id.append(elem.getUuidInterface());
634             id.append("/");
635             id.append(date != null ? date.getValue() : "null");
636
637             switch (granularityPeriod) {
638                 case Period15Min:
639                     pmData15mDB.write(elem, id.toString());
640                     break;
641                 case Period24Hours:
642                     pmData24hDB.write(elem, id.toString());
643                     break;
644                 case Unknown:
645                 default:
646                     LOG.debug("Unknown granularity {} id {}", granularityPeriod, id);
647                     break;
648             }
649         });
650
651     }
652
653     @NonNull
654     GranularityPeriodType nnGetGranularityPeriodType(@Nullable GranularityPeriodType granularityPeriod) {
655         return granularityPeriod != null ? granularityPeriod : GranularityPeriodType.Unknown;
656     }
657
658     @Override
659     public HtDatabaseClient getRawClient() {
660         return this.client;
661     }
662
663     @Override
664     public void writeGuiCutThroughData(Guicutthrough gcData, String nodeId) {
665         guiCutThroughDB.write(gcData, nodeId);
666     }
667
668     @Override
669     public int clearGuiCutThroughEntriesOfNode(String nodeName) {
670         guiCutThroughDB.remove(nodeName);
671         return 0;
672     }
673
674 }