code changes for platform hardening appc adapters
[appc.git] / appc-adapters / appc-dmaap-adapter / appc-dmaap-adapter-bundle / src / main / java / org / onap / appc / adapter / messaging / dmaap / impl / DmaapProducerImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.adapter.messaging.dmaap.impl;
26
27
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
30 import com.att.nsa.mr.client.MRBatchingPublisher;
31 import com.att.nsa.mr.client.MRClientFactory;
32 import org.apache.commons.lang3.StringUtils;
33 import org.onap.appc.adapter.message.Producer;
34 import org.onap.appc.adapter.messaging.dmaap.impl.DmaapUtil;
35 import org.onap.appc.configuration.Configuration;
36 import org.onap.appc.configuration.ConfigurationFactory;
37 import org.onap.appc.metricservice.MetricRegistry;
38 import org.onap.appc.metricservice.MetricService;
39 import org.onap.appc.metricservice.metric.Metric;
40 import org.onap.appc.metricservice.metric.MetricType;
41 import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric;
42 import org.onap.appc.metricservice.policy.PublishingPolicy;
43 import org.onap.appc.metricservice.publisher.LogPublisher;
44 import org.osgi.framework.BundleContext;
45 import org.osgi.framework.FrameworkUtil;
46 import org.osgi.framework.ServiceReference;
47 import java.io.IOException;
48 import java.util.Collection;
49 import java.util.HashSet;
50 import java.util.Properties;
51 import java.util.Set;
52 import java.util.UUID;
53 import java.util.concurrent.TimeUnit;
54
55
56 public class DmaapProducerImpl implements Producer {
57
58     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(DmaapProducerImpl.class);
59     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
60
61     private Set<String> topics = new HashSet<String>();
62
63     private Properties props = null;
64     private static MetricRegistry metricRegistry;
65     private boolean useHttps = false;
66     private boolean isMetricEnabled=false;
67     
68     private Set<MRBatchingPublisher> clients;
69
70     
71     public DmaapProducerImpl(Collection<String> urls, String topicName, String user, String password) {
72         this(urls, (Set<String>)null, user, password);
73         this.topics = new HashSet<>();
74         if (topicName != null) {
75             for (String topic : topicName.split(",")) {
76                 topics.add(topic);
77             }
78         }
79     }
80
81     public DmaapProducerImpl(Collection<String> urls, Set<String> topicNames, String user, String password) {
82         topics = topicNames;
83         if(urls == null || user == null || password == null){
84             throw new IllegalArgumentException("one of these mandaory argument is null: urls, user, password" );
85         }
86         this.props = new Properties();
87         String urlsStr = StringUtils.join(urls, ',');
88         props.setProperty("host",urlsStr);
89         props.setProperty("id", UUID.randomUUID().toString());
90         props.setProperty("username",user);
91         props.setProperty("password",password);
92     }
93     private void initMetric() {
94         LOG.debug("Metric getting initialized");
95         MetricService metricService = getMetricservice();
96         metricRegistry=metricService.createRegistry("APPC");
97        DmaapRequestCounterMetric dmaapKpiMetric = metricRegistry.metricBuilderFactory().
98                 dmaapRequestCounterBuilder().
99                 withName("DMAAP_KPI").withType(MetricType.COUNTER).
100                 withRecievedMessage(0)
101                 .withPublishedMessage(0)
102                 .build();
103         if(metricRegistry.register(dmaapKpiMetric)) {
104             Metric[] metrics = new Metric[]{dmaapKpiMetric};
105             LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics);
106             LogPublisher[] logPublishers = new LogPublisher[1];
107             logPublishers[0] = logPublisher;
108             PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory().
109                     scheduledPolicyBuilder().withPublishers(logPublishers).
110                     withMetrics(metrics).
111                     build();
112             LOG.debug("Policy getting initialized");
113             manuallyScheduledPublishingPolicy.init();
114             LOG.debug("Metric initialized");
115         }
116
117     }
118     private Set<MRBatchingPublisher> getClients() {
119         Set<MRBatchingPublisher> out = new HashSet<>();
120         for (String topic : topics) {
121             try {
122                 String topicProducerPropFileName = DmaapUtil.createProducerPropFile(topic,props);
123                 final MRBatchingPublisher client = MRClientFactory.createBatchingPublisher (topicProducerPropFileName);
124                 out.add(client);
125             } catch (Exception e) {
126                 e.printStackTrace();
127             }
128         }
129
130         return out;
131     }
132
133     @Override
134     public synchronized void updateCredentials(String key, String secret) {
135         LOG.info(String.format("Setting auth to %s for %s", key, this.toString()));
136         props.setProperty("user",String.valueOf(key));
137         props.setProperty("password",String.valueOf(secret));
138         clients = null;
139     }
140
141     @Override
142     public boolean post(String partition, String data) {
143         boolean success = true;
144         Properties properties=configuration.getProperties();
145         if(properties!=null && properties.getProperty("metric.enabled")!=null ){
146             isMetricEnabled=Boolean.valueOf(properties.getProperty("metric.enabled"));
147         }
148         if(isMetricEnabled){
149             initMetric();
150         }
151         
152         // Create clients once and reuse them on subsequent posts. This is 
153         // to support failover to other servers in the Dmaap cluster.
154         if ((clients == null) || (clients.isEmpty())) {
155             LOG.info("Getting CambriaBatchingPublisher Clients ...");
156             clients = getClients();
157         }
158         
159         for (MRBatchingPublisher client : clients) {
160             try {
161                 LOG.debug(String.format("Posting %s to %s", data, client));
162                 client.send(partition, data);
163             } catch (IOException e) {
164                 e.printStackTrace();
165                 success = false;
166             }
167         }
168         if(isMetricEnabled){
169             ( (DmaapRequestCounterMetric) metricRegistry.metric("DMAAP_KPI")).incrementPublishedMessage();
170         }
171         return success;
172     }
173
174     /**
175      * Close producer Dmaap client
176      */
177     @Override
178     public void close() {
179         if ((clients == null) || (clients.isEmpty())) {
180             return;
181         }
182
183         LOG.debug("Closing Dmaap producer clients....");
184         for (MRBatchingPublisher client : clients) {
185             try {
186                 client.close(1, TimeUnit.SECONDS);
187             }  catch (IOException | InterruptedException e) {
188                 LOG.warn(String.format("Failed to cleanly close Dmaap connection for [%s]", client));
189                 e.printStackTrace();
190             }
191         }
192     }
193
194     @Override
195     public void useHttps(boolean yes) {
196         useHttps = yes;
197     }
198
199     private MetricService getMetricservice() {
200         BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext();
201         ServiceReference sref = bctx.getServiceReference(MetricService.class.getName());
202         if (sref != null) {
203             LOG.info("Metric Service from bundlecontext");
204             return (MetricService) bctx.getService(sref);
205
206         } else {
207             LOG.info("Metric Service error from bundlecontext");
208             LOG.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService");
209             return null;
210
211         }
212     }
213
214     public  Metric getMetric(String name){
215         return metricRegistry.metric(name);
216     }
217 }