Initial TCA commit into DCAEGEN2
[dcaegen2/analytics/tca.git] / dcae-analytics-cdap-common / src / main / java / org / openecomp / dcae / apod / analytics / cdap / common / utils / DMaaPMRUtils.java
1 /*
2  * ===============================LICENSE_START======================================
3  *  dcae-analytics
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  *
11  *          http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *  ============================LICENSE_END===========================================
19  */
20
21 package org.openecomp.dcae.apod.analytics.cdap.common.utils;
22
23 import co.cask.cdap.api.metrics.Metrics;
24 import com.google.common.base.Optional;
25 import com.google.common.base.Stopwatch;
26 import org.openecomp.dcae.apod.analytics.cdap.common.CDAPMetricsConstants;
27 import org.openecomp.dcae.apod.analytics.common.exception.DCAEAnalyticsRuntimeException;
28 import org.openecomp.dcae.apod.analytics.common.utils.HTTPUtils;
29 import org.openecomp.dcae.apod.analytics.dmaap.domain.response.DMaaPMRSubscriberResponse;
30 import org.openecomp.dcae.apod.analytics.dmaap.service.subscriber.DMaaPMRSubscriber;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import java.util.List;
35
36 /**
37  * Utility common methods for DMaaP MR functionality
38  *
39  * @author Rajiv Singla . Creation Date: 2/6/2017.
40  */
41 public abstract class DMaaPMRUtils {
42
43     private static final Logger LOG = LoggerFactory.getLogger(DMaaPMRUtils.class);
44
45     private DMaaPMRUtils() {
46         // private constructor
47     }
48
49
50     /**
51      * Returns messages fetched from DMaaP MR Subscriber.
52      *
53      * @param subscriber DMaaP MR Subscriber instance
54      * @param metrics CDAP metrics
55      *
56      * @return messages fetched from DMaaP MR topic
57      */
58     public static Optional<List<String>> getSubscriberMessages(final DMaaPMRSubscriber subscriber,
59                                                                final Metrics metrics) {
60
61         final Optional<DMaaPMRSubscriberResponse> subscriberResponseOptional =
62                 getSubscriberResponse(subscriber, metrics);
63
64         // If response is not present, unable to proceed
65         if (!subscriberResponseOptional.isPresent()) {
66             return Optional.absent();
67         }
68
69         final DMaaPMRSubscriberResponse subscriberResponse = subscriberResponseOptional.get();
70
71         // If response code return by the subscriber call is not successful, unable to do proceed
72         if (!HTTPUtils.isSuccessfulResponseCode(subscriberResponse.getResponseCode())) {
73             LOG.error("Subscriber was unable to fetch messages properly.Subscriber Response Code: {} " +
74                     "Unable to proceed further....", subscriberResponse.getResponseCode());
75             metrics.count(CDAPMetricsConstants.DMAAP_MR_SUBSCRIBER_UNSUCCESSFUL_RESPONSES_METRIC, 1);
76             return Optional.absent();
77         }
78
79         LOG.debug("Subscriber HTTP Response Status Code match successful:  {}", subscriberResponse,
80                 HTTPUtils.HTTP_SUCCESS_STATUS_CODE);
81
82         final List<String> actualMessages = subscriberResponse.getFetchedMessages();
83
84         // If there are no message returned during from Subscriber, nothing to write to CDAP Stream
85         if (actualMessages.isEmpty()) {
86             LOG.debug("Subscriber Response has no messages. Nothing to write....");
87             metrics.count(CDAPMetricsConstants.DMAAP_MR_SUBSCRIBER_RESPONSES_WITH_NO_MESSAGES_METRIC, 1);
88             return Optional.absent();
89         }
90
91         LOG.debug("DMaaP MR Subscriber found new messages in DMaaP Topic. Message count: {}", actualMessages.size());
92         metrics.count(CDAPMetricsConstants.DMAAP_MR_SUBSCRIBER_TOTAL_MESSAGES_PROCESSED_METRIC, actualMessages.size());
93
94         return Optional.of(actualMessages);
95
96     }
97
98
99     /**
100      * Get Subscriber response and records time taken to fetch messages. Returns Optional.None if Subscriber response
101      * is null or response status code is not present
102      *
103      * @param subscriber - DMaaP Subscriber
104      * @param metrics - CDAP Metrics collector
105      *
106      * @return - Optional of Subscriber Response
107      */
108     public static Optional<DMaaPMRSubscriberResponse> getSubscriberResponse(final DMaaPMRSubscriber subscriber,
109                                                                             final Metrics metrics) {
110
111         // Record all response count from subscriber
112         metrics.count(CDAPMetricsConstants.DMAAP_MR_SUBSCRIBER_ALL_RESPONSES_COUNT_METRIC, 1);
113
114         // Check how long it took for subscriber to respond
115         final Stopwatch stopwatch = new Stopwatch();
116         stopwatch.start();
117
118         // Fetch messages from DMaaP MR Topic
119         DMaaPMRSubscriberResponse subscriberResponse = null;
120         try {
121             subscriberResponse = subscriber.fetchMessages();
122         } catch (DCAEAnalyticsRuntimeException e) {
123             LOG.error("Error while fetching messages for DMaaP MR Topic: {}", e);
124         }
125
126         stopwatch.stop();
127         final long subscriberResponseTimeMS = stopwatch.elapsedMillis();
128
129         // If response is null is null or response code is null, unable to proceed nothing to do
130         if (subscriberResponse == null || subscriberResponse.getResponseCode() == null) {
131             LOG.error("Subscriber Response is null or subscriber Response code is null. Unable to proceed further...");
132             return Optional.absent();
133         }
134
135         LOG.debug("Subscriber Response:{}, Subscriber HTTP Response Status Code {}, Subscriber Response Time(ms): {}",
136                 subscriberResponse, subscriberResponse.getResponseCode(), subscriberResponseTimeMS);
137
138         // Record subscriber response time
139         metrics.gauge(CDAPMetricsConstants.DMAAP_MR_SUBSCRIBER_RESPONSE_TIME_MS_METRIC, subscriberResponseTimeMS);
140
141         return Optional.of(subscriberResponse);
142     }
143
144 }