bump the version
[dmaap/messagerouter/msgrtr.git] / src / main / java / com / att / 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 com.att.mr.apiServer.metrics.cambria;
23
24 import java.io.IOException;
25 import java.net.InetAddress;
26 import java.net.UnknownHostException;
27 import java.text.SimpleDateFormat;
28 import java.util.Date;
29 import java.util.concurrent.ScheduledExecutorService;
30 import java.util.concurrent.ScheduledFuture;
31 import java.util.concurrent.TimeUnit;
32
33 import org.json.JSONException;
34 import org.json.JSONObject;
35 //import org.slf4j.Logger;
36 //import org.slf4j.LoggerFactory;
37
38 import com.att.dmf.mr.constants.CambriaConstants;
39 import com.att.dmf.mr.metrics.publisher.CambriaPublisher;
40 import com.att.dmf.mr.metrics.publisher.DMaaPCambriaClientFactory;
41 import com.att.eelf.configuration.EELFLogger;
42 import com.att.eelf.configuration.EELFManager;
43 import com.att.nsa.apiServer.metrics.cambria.MetricsSender;
44 import com.att.nsa.metrics.CdmMetricsRegistry;
45 import com.att.nsa.metrics.impl.CdmConstant;
46
47 /**
48  * MetricsSender will send the given metrics registry content as an event on the
49  * Cambria event broker to the given topic.
50  * 
51  * @author peter
52  *
53  */
54 public class DMaaPMetricsSender implements Runnable {
55         public static final String kSetting_CambriaEnabled = "metrics.send.cambria.enabled";
56         public static final String kSetting_CambriaBaseUrl = "metrics.send.cambria.baseUrl";
57         public static final String kSetting_CambriaTopic = "metrics.send.cambria.topic";
58         public static final String kSetting_CambriaSendFreqSecs = "metrics.send.cambria.sendEverySeconds";
59
60         /**
61          * Schedule a periodic send of the given metrics registry using the given
62          * settings container for the Cambria location, topic, and send frequency.
63          * <br/>
64          * <br/>
65          * If the enabled flag is false, this method returns null.
66          * 
67          * @param scheduler
68          * @param metrics
69          * @param settings
70          * @param defaultTopic
71          * @return a handle to the scheduled task
72          */
73         public static ScheduledFuture<?> sendPeriodically(ScheduledExecutorService scheduler, CdmMetricsRegistry metrics,
74                          String defaultTopic) {
75                 log.info("Inside : DMaaPMetricsSender : sendPeriodically");
76         String  cambriaSetting= com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,kSetting_CambriaEnabled);
77         boolean setEnable=true;
78         if (cambriaSetting!=null && cambriaSetting.equals("false") )
79         setEnable= false;
80
81                 if (setEnable) {
82                         String Setting_CambriaBaseUrl=com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,kSetting_CambriaEnabled);
83                         
84                         Setting_CambriaBaseUrl=Setting_CambriaBaseUrl==null?"localhost":Setting_CambriaBaseUrl;
85                         
86                         String Setting_CambriaTopic=com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,kSetting_CambriaTopic);
87                         if(Setting_CambriaTopic==null) Setting_CambriaTopic = "msgrtr.apinode.metrics.dmaap";     
88                         
89         
90                         
91                         String Setting_CambriaSendFreqSecs=com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,kSetting_CambriaSendFreqSecs);
92                         
93                         int _CambriaSendFreqSecs =30;
94                         if(Setting_CambriaSendFreqSecs!=null){
95                                  _CambriaSendFreqSecs = Integer.parseInt(Setting_CambriaSendFreqSecs);
96                         }
97                         
98
99                         return DMaaPMetricsSender.sendPeriodically(scheduler, metrics,
100                                         Setting_CambriaBaseUrl,Setting_CambriaTopic,_CambriaSendFreqSecs
101                                 );
102                         /*return DMaaPMetricsSender.sendPeriodically(scheduler, metrics,
103                                         settings.getString(kSetting_CambriaBaseUrl, "localhost"),
104                                         settings.getString(kSetting_CambriaTopic, defaultTopic),
105                                         settings.getInt(kSetting_CambriaSendFreqSecs, 30));*/
106                 } else {
107                         return null;
108                 }
109         }
110
111         /**
112          * Schedule a periodic send of the metrics registry to the given Cambria
113          * broker and topic.
114          * 
115          * @param scheduler
116          * @param metrics
117          *            the registry to send
118          * @param cambriaBaseUrl
119          *            the base URL for Cambria
120          * @param topic
121          *            the topic to publish on
122          * @param everySeconds
123          *            how frequently to publish
124          * @return a handle to the scheduled task
125          */
126         public static ScheduledFuture<?> sendPeriodically(ScheduledExecutorService scheduler, CdmMetricsRegistry metrics,
127                         String cambriaBaseUrl, String topic, int everySeconds) {
128                 return scheduler.scheduleAtFixedRate(new DMaaPMetricsSender(metrics, cambriaBaseUrl, topic), everySeconds,
129                                 everySeconds, TimeUnit.SECONDS);
130         }
131
132         /**
133          * Create a metrics sender.
134          * 
135          * @param metrics
136          * @param cambriaBaseUrl
137          * @param topic
138          */
139         public DMaaPMetricsSender(CdmMetricsRegistry metrics, String cambriaBaseUrl, String topic) {
140                 try {
141                         fMetrics = metrics;
142                         fHostname = InetAddress.getLocalHost().getHostName();
143
144                         // setup a "simple" publisher that will send metrics immediately
145                         fCambria = DMaaPCambriaClientFactory.createSimplePublisher(cambriaBaseUrl, topic);
146                 } catch (UnknownHostException e) {
147                         log.warn("Unable to get localhost address in MetricsSender constructor.", e);
148                         throw new RuntimeException(e);
149                 }
150         }
151
152         /**
153          * Send on demand.
154          */
155         public void send() {
156                 try {
157                         final JSONObject o = fMetrics.toJson();
158                         o.put("hostname", fHostname);
159                         o.put("now", System.currentTimeMillis());
160                         o.put("metricsSendTime", addTimeStamp());
161                         o.put("transactionEnabled", false);
162                         fCambria.send(fHostname, o.toString());
163                 } catch (JSONException e) {
164                         log.warn("Error posting metrics to Cambria: " + e.getMessage());
165                 } catch (IOException e) {
166                         log.warn("Error posting metrics to Cambria: " + e.getMessage());
167                 }
168         }
169
170         /**
171          * Run() calls send(). It's meant for use in a background-scheduled task.
172          */
173         @Override
174         public void run() {
175                 send();
176         }
177
178         private final CdmMetricsRegistry fMetrics;
179         private final CambriaPublisher fCambria;
180         private final String fHostname;
181
182         
183
184         private static final EELFLogger log = EELFManager.getInstance().getLogger(MetricsSender.class);
185         /**
186          * method creates and returnd CdmConstant object using current timestamp
187          * 
188          * @return
189          */
190         public CdmConstant addTimeStamp() {
191                 // Add the timestamp with every metrics send
192                 final long metricsSendTime = System.currentTimeMillis();
193                 final Date d = new Date(metricsSendTime);
194                 final String text = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz").format(d);
195                 return new CdmConstant(metricsSendTime / 1000, "Metrics Send Time (epoch); " + text);
196         }
197 }