aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java
blob: b17a66434a52f2c34421ea9c5aa0cc0a4d35478f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.sdc.be.model.cache;

import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.config.Configuration;
import org.openecomp.sdc.be.config.Configuration.ApplicationL1CacheCatalogInfo;
import org.openecomp.sdc.be.config.Configuration.ApplicationL2CacheConfig;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
import org.openecomp.sdc.be.dao.cassandra.ComponentCassandraDao;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.resources.data.ComponentCacheData;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.SerializationUtils;
import org.openecomp.sdc.common.util.ZipUtil;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Function;
import java.util.stream.Collectors;

@org.springframework.stereotype.Component("component-cache")
public class ComponentCache {

    private static final String COMPONENT_CACHE_IS_DISABLED = "Component Cache is disabled";

	private static final Logger log = Logger.getLogger(ComponentCache.class);

    @Autowired
    ComponentCassandraDao componentCassandraDao;

    @Autowired
    ToscaOperationFacade toscaOperationFacade;

    private Map<ComponentTypeEnum, Map<String, Component>> catalogInMemoryCache = new HashMap<>();
    private final ReentrantReadWriteLock rwCatalogLock = new ReentrantReadWriteLock();
    private final Lock rCatalogLock = rwCatalogLock.readLock();
    private final Lock wCatalogLock = rwCatalogLock.writeLock();

    boolean enabled = true;
    int catalogInMemorySizePerResource = 300;
    int catalogInMemorySizePerService = 200;
    int catalogInMemorySizePerProduct = 100;
    boolean catalogInMemoryEnabled = true;
    Map<ComponentTypeEnum, Integer> limitMemoryCatalogSizePerType = new HashMap<>();

    @PostConstruct
    public void init() {

        Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
        if (configuration != null) {
            ApplicationL2CacheConfig applicationL2Cache = configuration.getApplicationL2Cache();
            if (applicationL2Cache != null) {
                this.enabled = applicationL2Cache.isEnabled();

                ApplicationL1CacheCatalogInfo catalog = applicationL2Cache.getCatalogL1Cache();
                if (catalog != null) {
                    catalogInMemoryEnabled = catalog.getEnabled();
                    catalogInMemorySizePerResource = catalog.getResourcesSizeInCache();
                    catalogInMemorySizePerService = catalog.getServicesSizeInCache();
                    catalogInMemorySizePerProduct = catalog.getProductsSizeInCache();
                }
            }
        }

        ComponentTypeEnum[] typesForCache = { ComponentTypeEnum.RESOURCE, ComponentTypeEnum.SERVICE,
                ComponentTypeEnum.PRODUCT };
        for (ComponentTypeEnum typeEnum : typesForCache) {
            Map<String, Component> map = new HashMap<>();
            catalogInMemoryCache.put(typeEnum, map);
        }

        limitMemoryCatalogSizePerType.put(ComponentTypeEnum.RESOURCE, catalogInMemorySizePerResource);
        limitMemoryCatalogSizePerType.put(ComponentTypeEnum.SERVICE, catalogInMemorySizePerService);
        limitMemoryCatalogSizePerType.put(ComponentTypeEnum.PRODUCT, catalogInMemorySizePerProduct);
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public Either<Component, ActionStatus> getComponent(String componentUid, Long lastModificationTime,
            Function<Component, Component> filterFieldsFunc) {

        Either<ImmutablePair<Component, ComponentCacheData>, ActionStatus> componentFromCache = getComponentFromCache(
                componentUid, lastModificationTime, filterFieldsFunc);

        if (componentFromCache.isRight()) {
            return Either.right(componentFromCache.right().value());
        }

        return Either.left(componentFromCache.left().value().left);

    }

    public Either<List<ComponentCacheData>, ActionStatus> getAllComponentIdTimeAndType() {
        if (!isEnabled()) {
            return Either.right(ActionStatus.NOT_ALLOWED);
        }

        return componentCassandraDao
                .getAllComponentIdTimeAndType();

    }

    /**
     * get components for catalog
     *
     * @param components
     * @param componentTypeEnum
     * @return
     */
    @Deprecated
    public Either<ImmutableTriple<List<Component>, List<Component>, Set<String>>, ActionStatus> getComponentsForCatalog(
            Set<String> components, ComponentTypeEnum componentTypeEnum) {

        if (!isEnabled()) {
            log.debug("In getComponentsForCatalog for type {}. Cache is disabled.",
                    componentTypeEnum.name().toLowerCase());
            return Either.right(ActionStatus.NOT_ALLOWED);
        }
        log.debug("In getComponentsForCatalog for type {}", componentTypeEnum.name().toLowerCase());

        Function<List<Component>, List<Component>> filterFieldsFunc = this::filterForCatalog;

        Set<String> leftComponentsForSearch = new HashSet<>();
        leftComponentsForSearch.addAll(components);

        // get components from inmemory cache
        List<Component> componentsFromMemory = null;
        if (catalogInMemoryEnabled) {
            componentsFromMemory = getDataFromInMemoryCache(components, componentTypeEnum);
            log.debug("The number of components of type {} fetched from memory is {}",
                    componentTypeEnum.name().toLowerCase(),
                    componentsFromMemory == null ? 0 : componentsFromMemory.size());
            if (componentsFromMemory != null) {
                componentsFromMemory.forEach(p -> leftComponentsForSearch.remove(p.getUniqueId()));
            }
        } else {
            log.debug("Catalog InMemory cache is disabled");
        }

        log.debug("Number of components from type {} needed to fetch is {}", componentTypeEnum.name().toLowerCase(),
                leftComponentsForSearch.size());

        // get components from cassandra cache and filter each component
        Either<ImmutableTriple<List<Component>, List<Component>, Set<String>>, ActionStatus> result = getComponents(
                leftComponentsForSearch, filterFieldsFunc);

        if (result.isLeft()) {
            // add inmemory components to the valid components(not dirty)
            List<Component> foundComponents = result.left().value().getLeft();
            if (componentsFromMemory != null) {
                foundComponents.addAll(componentsFromMemory);
            }
            if (catalogInMemoryEnabled) {
                updateCatalogInMemoryCacheWithCertified(foundComponents, componentTypeEnum);
            }
        }

        return result;
    }

    /**
     * @param foundComponents
     * @param componentTypeEnum
     */
    private void updateCatalogInMemoryCacheWithCertified(List<Component> foundComponents,
            ComponentTypeEnum componentTypeEnum) {

        try {
            wCatalogLock.lock();

            long start = System.currentTimeMillis();
            Map<String, Component> map = catalogInMemoryCache.get(componentTypeEnum);
            int mapSizeBefore = map.size();
            map.clear();
            Map<String, Component> collect = foundComponents.stream()
                    .filter(p -> p.getLifecycleState() == LifecycleStateEnum.CERTIFIED)
                    .limit(limitMemoryCatalogSizePerType.get(componentTypeEnum))
                    .collect(Collectors.toMap(Component::getUniqueId, p -> p));
            map.putAll(collect);
            log.debug(
                    "Size of in memory cache for catalog {}(certified only): Before {}, After {}. Replacement Time is {} ms.",
                    componentTypeEnum.name().toLowerCase(), mapSizeBefore, map.size(),
                    System.currentTimeMillis() - start);
        } finally {
            wCatalogLock.unlock();
        }

    }

    private List<Component> getDataFromInMemoryCache(Set<String> components, ComponentTypeEnum componentTypeEnum) {
        List<Component> foundComponents = new ArrayList<>();

        try {

            rCatalogLock.lock();

            Map<String, Component> map = catalogInMemoryCache.get(componentTypeEnum);
            for (String compUid : components) {
                Component component = map.get(compUid);
                if (component != null) {
                    foundComponents.add(component);
                }
            }

        } finally {
            rCatalogLock.unlock();
        }

        return foundComponents;
    }

    /**
     *
     * get full components from cassandra. On each component apply filter
     * function in order to remove unused members
     *
     * @param components
     * @param filterFieldsFunc
     * @return <found components, found dirty components, not found components
     *         list> or Error
     */
    public Either<ImmutableTriple<List<Component>, List<Component>, Set<String>>, ActionStatus> getComponents(
            Set<String> components, Function<List<Component>, List<Component>> filterFieldsFunc) {

        if (!isEnabled()) {
            log.debug(COMPONENT_CACHE_IS_DISABLED);
            return Either.right(ActionStatus.NOT_ALLOWED);
        }

        Either<ImmutableTriple<List<Component>, List<Component>, Set<String>>, ActionStatus> componentsFull = getComponentsFull(
                components);

        if (componentsFull.isRight()) {
            return Either.right(componentsFull.right().value());
        }

        ImmutableTriple<List<Component>, List<Component>, Set<String>> immutableTriple = componentsFull.left().value();
        List<Component> foundResources = immutableTriple.left;
        List<Component> foundDirtyResources = immutableTriple.middle;
        Set<String> notFoundResources = immutableTriple.right;

        List<Component> filterdFoundResources = filterFieldsFunc.apply(foundResources);
        List<Component> filterdFoundDirtyResources = filterFieldsFunc.apply(foundDirtyResources);

        ImmutableTriple<List<Component>, List<Component>, Set<String>> result = new ImmutableTriple<>(
                filterdFoundResources, filterdFoundDirtyResources, notFoundResources);

        return Either.left(result);

    }

    public Either<ImmutableTriple<List<Component>, List<Component>, Set<String>>, ActionStatus> getComponentsForLeftPanel(
            ComponentTypeEnum componentTypeEnum, String internalComponentType, Set<String> filteredResources) {

        log.debug("In getComponentsForLeftPanel componentTypeEnum = {}, internalComponentType = {}",
                componentTypeEnum, internalComponentType);

        Function<List<Component>, List<Component>> filterFieldsFunc = this::filterForLeftPanel;

        return getComponents(filteredResources, filterFieldsFunc);

    }

    private List<Component> filterForLeftPanel(List<Component> components) {

        List<Component> result = new ArrayList<>();
        if (components != null) {
            components.forEach(p -> result.add(filterFieldsForLeftPanel(p)));
        }

        return result;
    }

    private List<Component> filterForCatalog(List<Component> components) {

        List<Component> result = new ArrayList<>();
        if (components != null) {
            components.forEach(p -> result.add(filterFieldsForCatalog(p)));
        }

        return result;
    }

    private Component filterFieldsForLeftPanel(Component component) {

        Component result = null;
        ComponentTypeEnum componentTypeEnum = component.getComponentType();
        switch (componentTypeEnum) {
        case RESOURCE:
            result = new Resource();
            copyFieldsForLeftPanel(component, result);
            break;
        case SERVICE:
            result = new Service();
            copyFieldsForLeftPanel(component, result);
            break;
        default:
            break;
        }

        return result;
    }

    private Component filterFieldsForCatalog(Component component) {

        Component result = null;
        ComponentTypeEnum componentTypeEnum = component.getComponentType();
        switch (componentTypeEnum) {
        case RESOURCE:
            result = new Resource();
            copyFieldsForCatalog(component, result);
            break;
        case SERVICE:
            result = new Service();
            copyFieldsForCatalog(component, result);
            break;
        case PRODUCT:
            result = new Product();
            copyFieldsForCatalog(component, result);
            break;
        default:
            break;
        }

        return result;
    }

    /**
     * Copy relevant fields to the filtered component for left panel
     *
     * @param component
     * @param filteredComponent
     */
    private void copyFieldsForLeftPanel(Component component, Component filteredComponent) {

        ComponentTypeEnum componentTypeEnum = component.getComponentType();
        filteredComponent.setCategories(component.getCategories());
        filteredComponent.setComponentType(component.getComponentType());
        if (ComponentTypeEnum.RESOURCE.equals(component.getComponentType())
                && ResourceTypeEnum.VL.equals(((ResourceMetadataDataDefinition) component
                        .getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType())) {
            filteredComponent.setCapabilities(component.getCapabilities());
            filteredComponent.setRequirements(component.getRequirements());
        }
        filteredComponent.setVersion(component.getVersion());
        filteredComponent.setDescription(component.getDescription());
        filteredComponent.setUniqueId(component.getUniqueId());
        filteredComponent.setIcon(component.getIcon());
        filteredComponent.setTags(component.getTags());
        filteredComponent.setLifecycleState(component.getLifecycleState());
        filteredComponent.setInvariantUUID(component.getInvariantUUID());
        filteredComponent.setUUID(component.getUUID());
        filteredComponent.setSystemName(component.getSystemName());
        filteredComponent.setName(component.getName());

        if (componentTypeEnum == ComponentTypeEnum.RESOURCE) {
            Resource resource = (Resource) component;
            Resource filteredResource = (Resource) filteredComponent;
            filteredResource.setToscaResourceName(resource.getToscaResourceName());
            filteredResource.setResourceType(resource.getResourceType());
        }
    }

    private void copyFieldsForCatalog(Component component, Component filteredComponent) {

        ComponentTypeEnum componentTypeEnum = component.getComponentType();
        filteredComponent.setCategories(component.getCategories());
        filteredComponent.setComponentType(component.getComponentType());
        filteredComponent.setVersion(component.getVersion());
        filteredComponent.setDescription(component.getDescription());
        filteredComponent.setUniqueId(component.getUniqueId());
        filteredComponent.setIcon(component.getIcon());
        filteredComponent.setTags(component.getTags());
        filteredComponent.setLifecycleState(component.getLifecycleState());
        filteredComponent.setSystemName(component.getSystemName());
        filteredComponent.setName(component.getName());
        filteredComponent.setLastUpdateDate(component.getLastUpdateDate());

        if (componentTypeEnum == ComponentTypeEnum.RESOURCE) {
            Resource resource = (Resource) component;
            Resource filteredResource = (Resource) filteredComponent;
            filteredResource.setToscaResourceName(resource.getToscaResourceName());
            filteredResource.setResourceType(resource.getResourceType());
        } else if (componentTypeEnum == ComponentTypeEnum.SERVICE) {
            Service service = (Service) component;
            Service filteredService = (Service) filteredComponent;
            filteredService.setDistributionStatus(service.getDistributionStatus());
        }
    }

    /**
     * get components from cache of a given list ou unique ids.
     *
     * for each component data from cassandra, unzip the data if needed and
     * deserialize the unzipped data to java object(Component).
     *
     * @param filteredResources
     * @return ImmutableTripple or ActionStatus. | |-- components |-- dirty
     *         components - components with dirty flag = true. |-- set of non
     *         cached components
     *
     */
    private Either<ImmutableTriple<List<Component>, List<Component>, Set<String>>, ActionStatus> getComponentsFull(
            Set<String> filteredResources) {

        if (!isEnabled()) {
            log.debug(COMPONENT_CACHE_IS_DISABLED);
            return Either.right(ActionStatus.NOT_ALLOWED);
        }

        List<Component> foundResources = new LinkedList<>();
        List<Component> foundDirtyResources = new LinkedList<>();
        Set<String> notFoundResources = new HashSet<>();
        ImmutableTriple<List<Component>, List<Component>, Set<String>> result = new ImmutableTriple<>(
                foundResources, foundDirtyResources, notFoundResources);

        long cassandraFetchStart = System.currentTimeMillis();
        List<String> uidsList = new ArrayList<>();
        uidsList.addAll(filteredResources);
        Either<List<ComponentCacheData>, ActionStatus> componentsFromCache = componentCassandraDao
                .getComponents(uidsList);

        long cassandraFetchEnd = System.currentTimeMillis();
        log.debug("Fetch time from cassandara of all components took {} ms",
                (cassandraFetchEnd - cassandraFetchStart));
        if (componentsFromCache.isRight()) {
            BeEcompErrorManager.getInstance().logInternalFlowError("FetchFromCache",
                    "Failed to fetch components from cache", ErrorSeverity.ERROR);
            return Either.right(componentsFromCache.right().value());
        }

        List<ComponentCacheData> list = componentsFromCache.left().value();
        log.debug("Number of components fetched from cassandra is {}", (list == null ? 0 : list.size()));
        if (list != null && !list.isEmpty()) {

            List<ComponentCacheData> filteredData = list.stream().filter(p -> filteredResources.contains(p.getId()))
                    .collect(Collectors.toList());
            log.debug("Number of components filterd is {}", filteredData == null ? 0 : filteredData.size());

            if (filteredData != null) {
                long desStart = System.currentTimeMillis();

                for (ComponentCacheData componentCacheData : filteredData) {

                    log.debug("Process uid {} from cache", componentCacheData.getId());

                    String compUid = componentCacheData.getId();

                    Either<? extends Component, Boolean> deserializeExt = convertComponentCacheToComponent(
                            componentCacheData);

                    if (deserializeExt.isLeft()) {
                        Component component = deserializeExt.left().value();
                        if (!componentCacheData.getIsDirty()) {
                            foundResources.add(component);
                        } else {
                            foundDirtyResources.add(component);
                        }
                    } else {
                        notFoundResources.add(compUid);
                    }

                }
                long desEnd = System.currentTimeMillis();
                log.debug("Deserialization and unzip of {} components took {} ms", filteredData.size(),
                        (desEnd - desStart));
            }
        }
        List<String> foundResourcesUid = foundResources.stream().map(Component::getUniqueId).collect(Collectors.toList());
        List<String> foundDirtyResourcesUid = foundDirtyResources.stream().map(Component::getUniqueId)
                .collect(Collectors.toList());
        log.debug("Number of processed components from cache is {}",
                (foundResourcesUid.size() + foundDirtyResourcesUid.size()));
        Set<String> notCachedResources = filteredResources.stream()
                .filter(p -> !foundResourcesUid.contains(p) && !foundDirtyResourcesUid.contains(p))
                .collect(Collectors.toSet());
        notFoundResources.addAll(notCachedResources);

        if (log.isDebugEnabled()) {
            log.debug("Number of components fetched is {}", foundResources.size());
            log.debug("Number of components fetched dirty is {}", foundDirtyResources.size());
            log.debug("Number of components non cached is {}", notCachedResources.size());
        }

        return Either.left(result);
    }

    private Either<? extends Component, Boolean> convertComponentCacheToComponent(
            ComponentCacheData componentCacheData) {

        String compUid = componentCacheData.getId();

        byte[] dataAsArray = componentCacheData.getDataAsArray();

        if (componentCacheData.getIsZipped()) {
            long startUnzip = System.nanoTime();
            dataAsArray = ZipUtil.unzip(dataAsArray);
            long endUnzip = System.nanoTime();
            log.trace("Unzip component {} took {} microsecond", compUid, (endUnzip - startUnzip) / 1000);
        }

        long startDes = System.nanoTime();

        Either<? extends Component, Boolean> deserializeExt = deserializeComponent(componentCacheData, dataAsArray);

        long endDes = System.nanoTime();
        log.trace("Deserialize component {} took {} microsecond", compUid, (endDes - startDes) / 1000);
        return deserializeExt;
    }

    private Either<? extends Component, Boolean> deserializeComponent(ComponentCacheData componentCacheData,
            byte[] dataAsArray) {
        String type = componentCacheData.getType();
        NodeTypeEnum typeEnum = NodeTypeEnum.getByNameIgnoreCase(type);

        Either<? extends Component, Boolean> deserializeExt = Either.right(false);
        switch (typeEnum) {
        case Resource:
            deserializeExt = SerializationUtils.deserializeExt(dataAsArray, Resource.class, componentCacheData.getId());
            break;
        case Service:
            deserializeExt = SerializationUtils.deserializeExt(dataAsArray, Service.class, componentCacheData.getId());
            break;
        case Product:
            deserializeExt = SerializationUtils.deserializeExt(dataAsArray, Product.class, componentCacheData.getId());
            break;
        default:
            break;
        }
        return deserializeExt;
    }

    public Either<Component, ActionStatus> getComponent(String componentUid) {

        return getComponent(componentUid, null, Function.identity());

    }

    private boolean saveComponent(String componentUid, Long lastModificationTime, NodeTypeEnum nodeTypeEnum,
            Component component) {

        log.trace("Going to save component {} of type {} in cache", componentUid, nodeTypeEnum.name().toLowerCase());

        boolean result = false;

        Either<byte[], Boolean> serializeExt = SerializationUtils.serializeExt(component);
        if (serializeExt.isLeft()) {
            byte[] serializedData = serializeExt.left().value();
            byte[] zipBytes;
            try {
                zipBytes = ZipUtil.zipBytes(serializedData);
                ComponentCacheData componentCacheData = new ComponentCacheData();
                componentCacheData.setDataAsArray(zipBytes);
                componentCacheData.setIsZipped(true);
                componentCacheData.setId(componentUid);
                componentCacheData.setModificationTime(new Date(lastModificationTime));
                componentCacheData.setType(component.getComponentType().name().toLowerCase());

                CassandraOperationStatus status = componentCassandraDao.saveComponent(componentCacheData);

                if (status == CassandraOperationStatus.OK) {
                    result = true;
                }

            } catch (IOException e) {
                log.debug("Failed to prepare component {} of type {} for cache", componentUid,
                        nodeTypeEnum.name().toLowerCase());
                if (log.isTraceEnabled()) {
                    log.trace("Failed to prepare component {} of type {} for cache",componentUid,nodeTypeEnum.name().toLowerCase());
                }
            }
        } else {
            log.debug("Failed to serialize component {} of type {} for cache", componentUid,
                    nodeTypeEnum.name().toLowerCase());
        }
        return result;
    }

    public boolean setComponent(Component component, NodeTypeEnum nodeTypeEnum) {

        boolean result = false;

        if (!isEnabled()) {
            log.debug(COMPONENT_CACHE_IS_DISABLED);
            return false;
        }

        String componentUid = component.getUniqueId();
        Long lastUpdateDate = component.getLastUpdateDate();

        result = saveComponent(componentUid, lastUpdateDate, nodeTypeEnum, component);

        return result;

    }

    /**
     * get components from cache of a given list ou unique ids.
     *
     * for each component data from cassandra, unzip the data if needed and
     * deserialize the unzipped data to java object(Component).
     *
     * @param filteredResources
     * @return ImmutableTripple or ActionStatus. | |-- components |-- set of non
     *         cached components
     *
     */
    private Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> getComponentsFull(
            Map<String, Long> filteredResources) {

        if (!isEnabled()) {
            log.debug(COMPONENT_CACHE_IS_DISABLED);
            return Either.right(ActionStatus.NOT_ALLOWED);
        }

        List<Component> foundResources = new LinkedList<>();
        Set<String> notFoundResources = new HashSet<>();
        ImmutablePair<List<Component>, Set<String>> result = new ImmutablePair<>(
                foundResources, notFoundResources);

        long cassandraFetchStart = System.currentTimeMillis();

        Either<ImmutablePair<List<ComponentCacheData>, Set<String>>, ActionStatus> componentsFromCache = componentCassandraDao
                .getComponents(filteredResources);

        long cassandraFetchEnd = System.currentTimeMillis();
        log.debug("Fetch time from cassandara of all components took {} ms",
                (cassandraFetchEnd - cassandraFetchStart));
        if (componentsFromCache.isRight()) {
            BeEcompErrorManager.getInstance().logInternalFlowError("FetchFromCache",
                    "Failed to fetch components from cache", ErrorSeverity.ERROR);
            return Either.right(componentsFromCache.right().value());
        }

        ImmutablePair<List<ComponentCacheData>, Set<String>> immutablePair = componentsFromCache.left().value();
        List<ComponentCacheData> list = immutablePair.getLeft();
        log.debug("Number of components fetched from cassandra is {}", (list == null ? 0 : list.size()));
        if (list != null && !list.isEmpty()) {

            log.debug("Number of components filterd is {}", list == null ? 0 : list.size());

            if (list != null) {
                long desStart = System.currentTimeMillis();

                for (ComponentCacheData componentCacheData : list) {

                    log.debug("Process uid {} from cache", componentCacheData.getId());

                    String compUid = componentCacheData.getId();

                    Either<? extends Component, Boolean> deserializeExt = convertComponentCacheToComponent(
                            componentCacheData);

                    if (deserializeExt.isLeft()) {
                        Component component = deserializeExt.left().value();
                        foundResources.add(component);
                    } else {
                        notFoundResources.add(compUid);
                    }

                }
                long desEnd = System.currentTimeMillis();
                log.debug("Deserialization and unzip of {} components took {} ms", list.size(), (desEnd - desStart));
            }
        }
        log.debug("Number of processed components from cache is {}", foundResources.size());

        Set<String> notFoundInCache = immutablePair.getRight();
        notFoundResources.addAll(notFoundInCache);

        if (log.isDebugEnabled()) {
            log.debug("Number of components fetched is {}", foundResources.size());
            log.debug("Number of components non cached is {}", notFoundResources.size());
        }

        return Either.left(result);
    }

    /**
     * get components for catalog
     *
     * @param components
     * @param componentTypeEnum
     * @return
     */
    public Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> getComponentsForCatalog(
            Map<String, Long> components, ComponentTypeEnum componentTypeEnum) {

        if (!isEnabled()) {
            log.debug("In getComponentsForCatalog for type {}. Cache is disabled.",
                    componentTypeEnum.name().toLowerCase());
            return Either.right(ActionStatus.NOT_ALLOWED);
        }
        log.debug("In getComponentsForCatalog for type {}", componentTypeEnum.name().toLowerCase());

        Function<List<Component>, List<Component>> filterFieldsFunc = this::filterForCatalog;

        Map<String, Long> leftComponentsForSearch = new HashMap<>();
        leftComponentsForSearch.putAll(components);

        // get components from inmemory cache
        List<Component> componentsFromMemory = null;
        if (catalogInMemoryEnabled) {
            componentsFromMemory = getDataFromInMemoryCache(components.keySet(), componentTypeEnum);
            log.debug("The number of components of type {} fetched from memory is {}",
                    componentTypeEnum.name().toLowerCase(),
                    componentsFromMemory == null ? 0 : componentsFromMemory.size());
            if (componentsFromMemory != null) {
                List<String> ignoredComponents = new ArrayList<>();
                for (Component componentFromMem : componentsFromMemory) {
                    if (componentFromMem.getLastUpdateDate().longValue() != components
                            .get(componentFromMem.getUniqueId()).longValue()) {
                        // Ignore the component from memory
                        ignoredComponents.add(componentFromMem.getUniqueId());
                    }
                }

                log.debug("Number of components from type {} ignored from memory cache is {}",
                        componentTypeEnum.name().toLowerCase(), ignoredComponents.size());
                // remove from memory result the components which are not valid
                componentsFromMemory = componentsFromMemory.stream()
                                                           .filter(p -> !ignoredComponents.contains(p.getUniqueId())).collect(Collectors.toList());
                // Remove from leftComponentsForSearch the valid components from
                // memory
                componentsFromMemory.forEach(p -> leftComponentsForSearch.remove(p.getUniqueId()));

            }
        } else {
            log.debug("Catalog InMemory cache is disabled");
        }

        log.debug("Number of components from type {} needed to fetch is {}", componentTypeEnum.name().toLowerCase(),
                leftComponentsForSearch.size());

        // get components from cassandra cache and filter each component
        Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> result = getComponents(
                leftComponentsForSearch, filterFieldsFunc);

        if (result.isLeft()) {
            // add inmemory components to the valid components(not dirty)
            List<Component> foundComponents = result.left().value().getLeft();
            if (componentsFromMemory != null) {
                foundComponents.addAll(componentsFromMemory);
            }
            if (catalogInMemoryEnabled) {
                updateCatalogInMemoryCacheWithCertified(foundComponents, componentTypeEnum);
            }
        }

        return result;
    }

    /**
     * @param components
     *            - Map of <componentUniqueId, last update date>
     * @param filterFieldsFunc
     * @return
     */
    public Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> getComponents(Map<String, Long> components,
            Function<List<Component>, List<Component>> filterFieldsFunc) {

        if (!isEnabled()) {
            log.debug(COMPONENT_CACHE_IS_DISABLED);
            return Either.right(ActionStatus.NOT_ALLOWED);
        }

        Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> componentsFull = getComponentsFull(
                components);

        if (componentsFull.isRight()) {
            return Either.right(componentsFull.right().value());
        }

        ImmutablePair<List<Component>, Set<String>> immutablePair = componentsFull.left().value();
        List<Component> foundResources = immutablePair.left;
        Set<String> notFoundResources = immutablePair.right;

        List<Component> filterdFoundResources = filterFieldsFunc.apply(foundResources);

        ImmutablePair<List<Component>, Set<String>> result = new ImmutablePair<>(
                filterdFoundResources, notFoundResources);

        return Either.left(result);

    }

    /**
     * get the component and its modification time from cache
     *
     * @param componentUid
     * @param filterFieldsFunc
     * @return
     */
    public Either<ImmutablePair<Component, Long>, ActionStatus> getComponentAndTime(String componentUid,
            Function<Component, Component> filterFieldsFunc) {

        Either<ImmutablePair<Component, ComponentCacheData>, ActionStatus> componentFromCache = getComponentFromCache(
                componentUid, null, filterFieldsFunc);

        if (componentFromCache.isRight()) {
            return Either.right(componentFromCache.right().value());
        }

        ImmutablePair<Component, ComponentCacheData> immutablePair = componentFromCache.left().value();

        ImmutablePair<Component, Long> result = new ImmutablePair<>(immutablePair.left,
                immutablePair.right.getModificationTime().getTime());

        return Either.left(result);
    }

    private Either<ImmutablePair<Component, ComponentCacheData>, ActionStatus> getComponentFromCache(
            String componentUid, Long lastModificationTime, Function<Component, Component> filterFieldsFunc) {
        if (!isEnabled()) {
            return Either.right(ActionStatus.NOT_ALLOWED);
        }

        Either<ComponentCacheData, ActionStatus> componentRes = componentCassandraDao.getComponent(componentUid);

        if (componentRes.isRight()) {
            return Either.right(componentRes.right().value());
        }

        ComponentCacheData componentCacheData = componentRes.left().value();

        if (lastModificationTime != null) {
            long cacheCompModificationTime = componentCacheData.getModificationTime().getTime();
            if (lastModificationTime != cacheCompModificationTime) {
                log.debug(
                        "Component {} found in cache but its modification time {} does not match to the timestamp in cache {}.",
                        componentUid, lastModificationTime, cacheCompModificationTime);
                return Either.right(ActionStatus.INVALID_CONTENT);
            }
        }

        Either<? extends Component, Boolean> convertRes = convertComponentCacheToComponent(componentCacheData);
        if (convertRes.isRight()) {
            return Either.right(ActionStatus.CONVERT_COMPONENT_ERROR);
        }

        Component component = convertRes.left().value();

        Component filteredComponent = component;
        if (filterFieldsFunc != null) {
            filteredComponent = filterFieldsFunc.apply(component);
        }

        ImmutablePair<Component, ComponentCacheData> result = new ImmutablePair<>(
                filteredComponent, componentCacheData);

        return Either.left(result);
    }

    public ActionStatus deleteComponentFromCache(String id) {
        if (!isEnabled()) {
            return ActionStatus.NOT_ALLOWED;
        }
        CassandraOperationStatus status = this.componentCassandraDao.deleteComponent(id);
        if (CassandraOperationStatus.OK.equals(status)) {
            return ActionStatus.OK;
        } else {
            log.debug("delete component failed with error {}", status);
            return ActionStatus.GENERAL_ERROR;
        }
    }

}