DMAAP-MR - Merge MR repos
[dmaap/messagerouter/messageservice.git] / src / main / java / org / onap / dmaap / mr / apiServer / metrics / cambria / DMaaPMetricsSender.java
1 /*******************************************************************************
2  *  ============LICENSE_START=======================================================
3  *  org.onap.dmaap
4  *  ================================================================================
5  *  Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  *  ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *        http://www.apache.org/licenses/LICENSE-2.0
11 *  
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *  ============LICENSE_END=========================================================
18  *  
19  *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
20  *  
21  *******************************************************************************/
22 package org.onap.dmaap.mr.apiServer.metrics.cambria;
23
24 import com.att.eelf.configuration.EELFLogger;
25 import com.att.eelf.configuration.EELFManager;
26 import com.att.nsa.apiServer.metrics.cambria.MetricsSender;
27 import com.att.nsa.metrics.CdmMetricsRegistry;
28 import com.att.nsa.metrics.impl.CdmConstant;
29 import org.json.JSONException;
30 import org.json.JSONObject;
31 import org.onap.dmaap.dmf.mr.constants.CambriaConstants;
32 import org.onap.dmaap.dmf.mr.metrics.publisher.CambriaPublisher;
33 import org.onap.dmaap.dmf.mr.metrics.publisher.DMaaPCambriaClientFactory;
34
35 import java.io.IOException;
36 import java.net.InetAddress;
37 import java.net.UnknownHostException;
38 import java.text.SimpleDateFormat;
39 import java.util.Date;
40 import java.util.concurrent.ScheduledExecutorService;
41 import java.util.concurrent.ScheduledFuture;
42 import java.util.concurrent.TimeUnit;
43
44 /**
45  * MetricsSender will send the given metrics registry content as an event on the
46  * Cambria event broker to the given topic.
47  * 
48  * @author peter
49  *
50  */
51 public class DMaaPMetricsSender implements Runnable {
52         public static final String kSetting_CambriaEnabled = "metrics.send.cambria.enabled";
53         public static final String kSetting_CambriaBaseUrl = "metrics.send.cambria.baseUrl";
54         public static final String kSetting_CambriaTopic = "metrics.send.cambria.topic";
55         public static final String kSetting_CambriaSendFreqSecs = "metrics.send.cambria.sendEverySeconds";
56
57         /**
58          * Schedule a periodic send of the given metrics registry using the given
59          * settings container for the Cambria location, topic, and send frequency.
60          * <br/>
61          * <br/>
62          * If the enabled flag is false, this method returns null.
63          * 
64          * @param scheduler
65          * @param metrics
66          * @param settings
67          * @param defaultTopic
68          * @return a handle to the scheduled task
69          */
70         public static ScheduledFuture<?> sendPeriodically(ScheduledExecutorService scheduler, CdmMetricsRegistry metrics,
71                          String defaultTopic) {
72                 log.info("Inside : DMaaPMetricsSender : sendPeriodically");
73         String  cambriaSetting= com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,kSetting_CambriaEnabled);
74         boolean setEnable=true;
75         if (cambriaSetting!=null && cambriaSetting.equals("false") )
76         setEnable= false;
77
78                 if (setEnable) {
79                         String Setting_CambriaBaseUrl=com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,kSetting_CambriaEnabled);
80                         
81                         Setting_CambriaBaseUrl=Setting_CambriaBaseUrl==null?"localhost":Setting_CambriaBaseUrl;
82                         
83                         String Setting_CambriaTopic=com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,kSetting_CambriaTopic);
84                         if(Setting_CambriaTopic==null) Setting_CambriaTopic = "msgrtr.apinode.metrics.dmaap";     
85                         
86         
87                         
88                         String Setting_CambriaSendFreqSecs=com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,kSetting_CambriaSendFreqSecs);
89                         
90                         int _CambriaSendFreqSecs =30;
91                         if(Setting_CambriaSendFreqSecs!=null){
92                                  _CambriaSendFreqSecs = Integer.parseInt(Setting_CambriaSendFreqSecs);
93                         }
94                         
95
96                         return sendPeriodically(scheduler, metrics,
97                                         Setting_CambriaBaseUrl,Setting_CambriaTopic,_CambriaSendFreqSecs
98                                 );
99                         /*return DMaaPMetricsSender.sendPeriodically(scheduler, metrics,
100                                         settings.getString(kSetting_CambriaBaseUrl, "localhost"),
101                                         settings.getString(kSetting_CambriaTopic, defaultTopic),
102                                         settings.getInt(kSetting_CambriaSendFreqSecs, 30));*/
103                 } else {
104                         return null;
105                 }
106         }
107
108         /**
109          * Schedule a periodic send of the metrics registry to the given Cambria
110          * broker and topic.
111          * 
112          * @param scheduler
113          * @param metrics
114          *            the registry to send
115          * @param cambriaBaseUrl
116          *            the base URL for Cambria
117          * @param topic
118          *            the topic to publish on
119          * @param everySeconds
120          *            how frequently to publish
121          * @return a handle to the scheduled task
122          */
123         public static ScheduledFuture<?> sendPeriodically(ScheduledExecutorService scheduler, CdmMetricsRegistry metrics,
124                         String cambriaBaseUrl, String topic, int everySeconds) {
125                 return scheduler.scheduleAtFixedRate(new org.onap.dmaap.mr.apiServer.metrics.cambria.DMaaPMetricsSender(metrics, cambriaBaseUrl, topic), everySeconds,
126                                 everySeconds, TimeUnit.SECONDS);
127         }
128
129         /**
130          * Create a metrics sender.
131          * 
132          * @param metrics
133          * @param cambriaBaseUrl
134          * @param topic
135          */
136         public DMaaPMetricsSender(CdmMetricsRegistry metrics, String cambriaBaseUrl, String topic) {
137                 try {
138                         fMetrics = metrics;
139                         fHostname = InetAddress.getLocalHost().getHostName();
140
141                         // setup a "simple" publisher that will send metrics immediately
142                         fCambria = DMaaPCambriaClientFactory.createSimplePublisher(cambriaBaseUrl, topic);
143                 } catch (UnknownHostException e) {
144                         log.warn("Unable to get localhost address in MetricsSender constructor.", e);
145                         throw new RuntimeException(e);
146                 }
147         }
148
149         /**
150          * Send on demand.
151          */
152         public void send() {
153                 try {
154                         final JSONObject o = fMetrics.toJson();
155                         o.put("hostname", fHostname);
156                         o.put("now", System.currentTimeMillis());
157                         o.put("metricsSendTime", addTimeStamp());
158                         o.put("transactionEnabled", false);
159                         fCambria.send(fHostname, o.toString());
160                 } catch (JSONException e) {
161                         log.warn("Error posting metrics to Cambria: " + e.getMessage());
162                 } catch (IOException e) {
163                         log.warn("Error posting metrics to Cambria: " + e.getMessage());
164                 }
165         }
166
167         /**
168          * Run() calls send(). It's meant for use in a background-scheduled task.
169          */
170         @Override
171         public void run() {
172                 send();
173         }
174
175         private final CdmMetricsRegistry fMetrics;
176         private final CambriaPublisher fCambria;
177         private final String fHostname;
178
179         
180
181         private static final EELFLogger log = EELFManager.getInstance().getLogger(MetricsSender.class);
182         /**
183          * method creates and returnd CdmConstant object using current timestamp
184          * 
185          * @return
186          */
187         public CdmConstant addTimeStamp() {
188                 // Add the timestamp with every metrics send
189                 final long metricsSendTime = System.currentTimeMillis();
190                 final Date d = new Date(metricsSendTime);
191                 final String text = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz").format(d);
192                 return new CdmConstant(metricsSendTime / 1000, "Metrics Send Time (epoch); " + text);
193         }
194 }