b7997ef90e54095503aec60ffd5e22e9f1d528c6
[dcaegen2/collectors/ves.git] / src / main / java / org / onap / dcae / common / publishing / DMaaPPublishersCache.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dcaegen2.collectors.ves
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2018 Nokia. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.dcae.common.publishing;
22
23 import com.att.nsa.cambria.client.CambriaBatchingPublisher;
24 import com.google.common.cache.*;
25 import io.vavr.collection.Map;
26 import io.vavr.control.Option;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 import javax.annotation.Nonnull;
31 import java.io.IOException;
32 import java.util.concurrent.TimeUnit;
33 import java.util.concurrent.atomic.AtomicReference;
34
35 import static io.vavr.API.Option;
36 import static org.onap.dcae.common.publishing.VavrUtils.f;
37
38 /**
39  * @author Pawel Szalapski (pawel.szalapski@nokia.com)
40  */
41 class DMaaPPublishersCache {
42
43     private static final Logger log = LoggerFactory.getLogger(DMaaPPublishersCache.class);
44     private final LoadingCache<String, CambriaBatchingPublisher> publishersCache;
45     private AtomicReference<Map<String, PublisherConfig>> dMaaPConfiguration;
46
47     DMaaPPublishersCache(Map<String, PublisherConfig> dMaaPConfiguration) {
48         this.dMaaPConfiguration = new AtomicReference<>(dMaaPConfiguration);
49         this.publishersCache = CacheBuilder.newBuilder()
50                 .removalListener(new OnPublisherRemovalListener())
51                 .build(new CambriaPublishersCacheLoader());
52     }
53
54     DMaaPPublishersCache(CambriaPublishersCacheLoader dMaaPPublishersCacheLoader,
55                          OnPublisherRemovalListener onPublisherRemovalListener,
56                          Map<String, PublisherConfig> dMaaPConfiguration) {
57         this.dMaaPConfiguration = new AtomicReference<>(dMaaPConfiguration);
58         this.publishersCache = CacheBuilder.newBuilder()
59                 .removalListener(onPublisherRemovalListener)
60                 .build(dMaaPPublishersCacheLoader);
61     }
62
63     Option<CambriaBatchingPublisher> getPublisher(String streamID) {
64         try {
65             return Option(publishersCache.getUnchecked(streamID));
66         } catch (Exception e) {
67             log.warn("Could not create / load Cambria Publisher for streamID", e);
68             return Option.none();
69         }
70     }
71
72     void closePublisherFor(String streamId) {
73         publishersCache.invalidate(streamId);
74     }
75
76     synchronized void reconfigure(Map<String, PublisherConfig> newConfig) {
77         Map<String, PublisherConfig> currentConfig = dMaaPConfiguration.get();
78         Map<String, PublisherConfig> removedConfigurations = currentConfig
79                 .filterKeys(domain -> !newConfig.containsKey(domain));
80         Map<String, PublisherConfig> changedConfigurations = newConfig
81                 .filterKeys(e -> currentConfig.containsKey(e) && !currentConfig.get(e).equals(newConfig.get(e)));
82         dMaaPConfiguration.set(newConfig);
83         removedConfigurations.merge(changedConfigurations).forEach(e -> publishersCache.invalidate(e._1));
84     }
85
86     static class OnPublisherRemovalListener implements RemovalListener<String, CambriaBatchingPublisher> {
87
88         @Override
89         public void onRemoval(@Nonnull RemovalNotification<String, CambriaBatchingPublisher> notification) {
90             CambriaBatchingPublisher publisher = notification.getValue();
91             if (publisher != null) { // The value might get Garbage Collected at this moment, regardless of @Nonnull
92                 try {
93                     int timeout = 20;
94                     TimeUnit unit = TimeUnit.SECONDS;
95                     java.util.List<?> stuck = publisher.close(timeout, unit);
96                     if (!stuck.isEmpty()) {
97                         log.error(f("Publisher got stuck and did not manage to close in '%s' '%s', "
98                                 + "%s messages were dropped", stuck.size(), timeout, unit));
99                     }
100                 } catch (InterruptedException | IOException e) {
101                     log.error("Could not close Cambria publisher, some messages might have been dropped", e);
102                     Thread.currentThread().interrupt();
103                 }
104             }
105         }
106     }
107
108     class CambriaPublishersCacheLoader extends CacheLoader<String, CambriaBatchingPublisher> {
109
110         @Override
111         public CambriaBatchingPublisher load(@Nonnull String domain) {
112             return dMaaPConfiguration.get()
113                     .get(domain)
114                     .toTry(() -> new RuntimeException(
115                             f("DMaaP configuration contains no configuration for domain: '%s'", domain)))
116                     .flatMap(DMaaPPublishersBuilder::buildPublisher)
117                     .get();
118         }
119     }
120
121 }