aboutsummaryrefslogtreecommitdiffstats
path: root/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/provider/DmaapSimProvider.java
blob: afbe10f5145efcfe4aa2e36e9acc920cd9de6ac9 (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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019, 2023 Nordix Foundation.
 *  Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
 *  Modifications Copyright (C) 2021 Bell Canada. 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.models.sim.dmaap.provider;

import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import lombok.Getter;
import lombok.Setter;
import org.onap.policy.common.utils.services.ServiceManagerContainer;
import org.onap.policy.models.sim.dmaap.parameters.DmaapSimParameterGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Provider to simulate DMaaP.
 *
 * @author Liam Fallon (liam.fallon@est.tech)
 */
public class DmaapSimProvider extends ServiceManagerContainer {
    private static final Logger LOGGER = LoggerFactory.getLogger(DmaapSimProvider.class);

    @Getter
    @Setter
    private static DmaapSimProvider instance;

    /**
     * Maps a topic name to its data.
     */
    private final Map<String, TopicData> topic2data = new ConcurrentHashMap<>();

    /**
     * Thread used to remove idle consumers from the topics.
     */
    private ScheduledExecutorService timerPool;


    /**
     * Constructs the object.
     *
     * @param params parameters
     */
    public DmaapSimProvider(DmaapSimParameterGroup params) {
        addAction("Topic Sweeper", () -> {
            timerPool = makeTimerPool();
            timerPool.scheduleWithFixedDelay(new SweeperTask(), params.getTopicSweepSec(), params.getTopicSweepSec(),
                            TimeUnit.SECONDS);
        }, () -> timerPool.shutdown());
    }

    /**
     * Process a DMaaP message.
     *
     * @param topicName the topic name
     * @param dmaapMessage the message to process
     * @return a response to the message
     */
    @SuppressWarnings("unchecked")
    public Response processDmaapMessagePut(final String topicName, final Object dmaapMessage) {
        LOGGER.debug("Topic: {}, Received DMaaP message(s): {}", topicName, dmaapMessage);

        List<Object> lst;

        if (dmaapMessage instanceof List) {
            lst = (List<Object>) dmaapMessage;
        } else {
            lst = Collections.singletonList(dmaapMessage);
        }

        TopicData topic = topic2data.get(topicName);

        /*
         * Write all messages and return the count. If the topic doesn't exist yet, then
         * there are no subscribers to receive the messages, thus treat it as if all
         * messages were published.
         */
        int nmessages = (topic != null ? topic.write(lst) : lst.size());

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("serverTimeMs", 0);
        map.put("count", nmessages);

        return Response.status(Response.Status.OK).entity(map).build();
    }

    /**
     * Wait for and return a DMaaP message.
     *
     * @param topicName The topic to wait on
     * @param consumerGroup the consumer group that is waiting
     * @param consumerId the consumer ID that is waiting
     * @param limit the maximum number of messages to get
     * @param timeoutMs the length of time to wait for
     * @return the DMaaP message or
     */
    public Response processDmaapMessageGet(final String topicName, final String consumerGroup, final String consumerId,
                    final int limit, final long timeoutMs) {

        LOGGER.debug("Topic: {}, Request for DMaaP message: {}: {} with limit={} timeout={}", topicName, consumerGroup,
                        consumerId, limit, timeoutMs);

        try {
            List<String> lst = topic2data.computeIfAbsent(topicName, this::makeTopicData).read(consumerGroup, limit,
                            timeoutMs);

            LOGGER.debug("Topic: {}, Retrieved {} messages for: {}: {}", topicName, lst.size(), consumerGroup,
                            consumerId);
            return Response.status(Status.OK).entity(lst).build();

        } catch (InterruptedException e) {
            LOGGER.warn("Topic: {}, Request for DMaaP message interrupted: {}: {}", topicName, consumerGroup,
                            consumerId, e);
            Thread.currentThread().interrupt();
            return Response.status(Status.GONE).entity(Collections.emptyList()).build();
        }
    }

    /**
     * Returns the list of default topics.
     *
     * @return the topic list
     */
    public Response processDmaapTopicsGet() {

        LOGGER.debug("Request for listing DMaaP topics");
        var response = new DmaapGetTopicResponse();
        response.setTopics(List.of("POLICY-PDP-PAP", "POLICY-NOTIFICATION", "unauthenticated.DCAE_CL_OUTPUT",
                        "POLICY-CL-MGT"));
        return Response.status(Status.OK).entity(response).build();
    }

    /**
     * Task to remove idle consumers from each topic.
     */
    private class SweeperTask implements Runnable {
        @Override
        public void run() {
            topic2data.values().forEach(TopicData::removeIdleConsumers);
        }
    }

    // the following methods may be overridden by junit tests

    /**
     * Makes a new timer pool.
     *
     * @return a new timer pool
     */
    protected ScheduledExecutorService makeTimerPool() {
        return Executors.newScheduledThreadPool(1);
    }

    /**
     * Makes a new topic.
     *
     * @param topicName topic name
     * @return a new topic
     */
    protected TopicData makeTopicData(String topicName) {
        return new TopicData(topicName);
    }
}