summaryrefslogtreecommitdiffstats
path: root/dcae-analytics/dcae-analytics-web/src/main/java/org/onap/dcae/analytics/web/dmaap/MrSubscriberPollingAdvice.java
blob: 2ebb38d1524638241b43c9e65387c1870adade71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/*
 * ================================================================================
 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 *
 */

package org.onap.dcae.analytics.web.dmaap;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.onap.dcae.analytics.model.AnalyticsHttpConstants;
import org.onap.dcae.analytics.model.DmaapMrConstants;
import org.onap.dcae.analytics.tca.core.util.LogSpec;
import org.onap.dcae.analytics.web.util.AnalyticsHttpUtils;
import org.onap.dcae.utils.eelf.logger.api.log.EELFLogFactory;
import org.onap.dcae.utils.eelf.logger.api.log.EELFLogger;
import org.onap.dcae.utils.eelf.logger.api.spec.DebugLogSpec;
import org.springframework.http.HttpStatus;
import org.springframework.integration.handler.advice.AbstractRequestHandlerAdvice;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.util.DynamicPeriodicTrigger;
import org.springframework.messaging.Message;

/**
 * A polling advice which can auto adjust polling intervals depending on DMaaP MR message availability.
 * Can be configured to slow down polling when messages are not available and increase polling when messages are
 * indeed available.
 * <p>
 * The next polling interval is <b>increased</b> by given step up delta if message is <b>not found</b> up to maximum
 * Polling Interval
 * <br>
 * The next polling interval is <b>decreased</b> by step down delta if message <b>is found</b> up to minimum
 * polling interval
 *
 * @author Rajiv Singla
 */
public class MrSubscriberPollingAdvice extends AbstractRequestHandlerAdvice {

    private static final EELFLogger eelfLogger = EELFLogFactory.getLogger(MrSubscriberPollingAdvice.class);

    private final DynamicPeriodicTrigger trigger;
    private final int minPollingInterval;
    private final int stepUpPollingDelta;
    private final int maxPollingInterval;
    private final int stepDownPollingDelta;

    private final AtomicInteger nextPollingInterval;

    /**
     * Creates variable polling intervals based on message availability.
     *
     * @param trigger Dynamic Trigger instance
     * @param minPollingInterval Minimum polling interval
     * @param stepUpPollingDelta Delta by which next polling interval will be increased when message is not found
     * @param maxPollingInterval Maximum polling interval
     * @param stepDownPollingDelta Delta by which next polling interval will be decreased when message is found
     */
    public MrSubscriberPollingAdvice(final DynamicPeriodicTrigger trigger,
                                     final int minPollingInterval,
                                     final int stepUpPollingDelta,
                                     final int maxPollingInterval,
                                     final int stepDownPollingDelta) {
        this.trigger = trigger;
        this.minPollingInterval = minPollingInterval;
        this.stepUpPollingDelta = stepUpPollingDelta;
        this.maxPollingInterval = maxPollingInterval;
        this.stepDownPollingDelta = stepDownPollingDelta;
        nextPollingInterval = new AtomicInteger(minPollingInterval);
    }

    @Override
    @SuppressWarnings("unchecked")
    protected Object doInvoke(final ExecutionCallback callback, final Object target, final Message<?> message)
            throws Exception {

        // execute call back
        Object result = callback.execute();

        // if result is not of type message builder just return
        if (!(result instanceof MessageBuilder)) {
            return result;
        }

        final MessageBuilder<String> resultMessageBuilder = (MessageBuilder<String>) result;
        final String payload = resultMessageBuilder.getPayload();
        final Map<String, Object> headers = resultMessageBuilder.getHeaders();
        final Object httpStatusCode = headers.get(AnalyticsHttpConstants.HTTP_STATUS_CODE_HEADER_KEY);

        // get http status code
        if (httpStatusCode == null) {
            return result;
        }
        final HttpStatus httpStatus = HttpStatus.resolve(Integer.parseInt(httpStatusCode.toString()));


        // if status code is present and successful apply polling adjustments
        if (httpStatus != null && httpStatus.is2xxSuccessful()) {
            final boolean areMessagesPresent = areMessagesPresent(payload);
            updateNextPollingInterval(areMessagesPresent);

            final String requestId = AnalyticsHttpUtils.getRequestId(message.getHeaders());
            final String transactionId = AnalyticsHttpUtils.getTransactionId(message.getHeaders());
            final DebugLogSpec debugLogSpec = LogSpec.createDebugLogSpec(requestId);
            eelfLogger.debugLog().debug("Request Id: {}, Transaction Id: {}, Messages Present: {}, " +
                            "Next Polling Interval will be: {}", debugLogSpec, requestId, transactionId,
                            String.valueOf(areMessagesPresent), nextPollingInterval.toString());

            trigger.setPeriod(nextPollingInterval.get());

            // if no messages were found in dmaap poll - terminate further processing
            if (!areMessagesPresent) {
                eelfLogger.debugLog().debug("Request Id: {}, Transaction Id: {}, No new messages found in DMaaP MR Response. " +
                        "No further processing required", debugLogSpec, requestId, transactionId);
                return null;
            }

        }

        return result;
    }

    private boolean areMessagesPresent(final String payload) {

        return !(payload.isEmpty() || payload.equals(DmaapMrConstants.SUBSCRIBER_EMPTY_MESSAGE_RESPONSE_STRING));
    }

    private void updateNextPollingInterval(final boolean areMessagesPresent) {
        if (areMessagesPresent) {
            nextPollingInterval.getAndUpdate(interval -> interval - stepDownPollingDelta <= minPollingInterval ?
                    minPollingInterval : interval - stepDownPollingDelta);
        } else {
            nextPollingInterval.getAndUpdate(interval -> interval + stepUpPollingDelta >= maxPollingInterval ?
                    maxPollingInterval : interval + stepUpPollingDelta);
        }
    }
}