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