Use new addTopic() method in models
[policy/models.git] / models-sim / policy-models-sim-pdp / src / main / java / org / onap / policy / models / sim / pdp / PdpSimulatorActivator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  *  Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
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  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.models.sim.pdp;
23
24 import java.util.List;
25 import java.util.Random;
26 import lombok.Getter;
27 import lombok.Setter;
28 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
29 import org.onap.policy.common.endpoints.event.comm.TopicSink;
30 import org.onap.policy.common.endpoints.event.comm.TopicSource;
31 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
32 import org.onap.policy.common.utils.services.Registry;
33 import org.onap.policy.common.utils.services.ServiceManager;
34 import org.onap.policy.common.utils.services.ServiceManagerException;
35 import org.onap.policy.models.pdp.enums.PdpMessageType;
36 import org.onap.policy.models.sim.pdp.comm.PdpStateChangeListener;
37 import org.onap.policy.models.sim.pdp.comm.PdpStatusPublisher;
38 import org.onap.policy.models.sim.pdp.comm.PdpUpdateListener;
39 import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException;
40 import org.onap.policy.models.sim.pdp.exception.PdpSimulatorRunTimeException;
41 import org.onap.policy.models.sim.pdp.handler.PdpMessageHandler;
42 import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterGroup;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * This class activates the PdpSimulator as a complete service together with all its handlers.
48  *
49  * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
50  */
51 public class PdpSimulatorActivator {
52
53     private static final Logger LOGGER = LoggerFactory.getLogger(PdpSimulatorActivator.class);
54     private final PdpSimulatorParameterGroup pdpSimulatorParameterGroup;
55     private List<TopicSink> topicSinks;// topics to which pdp sends pdp status
56     private List<TopicSource> topicSources; // topics to which pdp listens to for messages from pap.
57     private static final String[] MSG_TYPE_NAMES = { "messageName" };
58     private static final Random RANDOM = new Random();
59
60     /**
61      * Listens for messages on the topic, decodes them into a message, and then dispatches them.
62      */
63     private final MessageTypeDispatcher msgDispatcher;
64
65     /**
66      * Used to manage the services.
67      */
68     private ServiceManager manager;
69
70
71     @Getter
72     @Setter(lombok.AccessLevel.PRIVATE)
73     private volatile boolean alive = false;
74
75     /**
76      * Instantiate the activator for onappf PDP-A.
77      *
78      * @param pdpSimulatorParameterGroup the parameters for the onappf PDP-A service
79      */
80     public PdpSimulatorActivator(final PdpSimulatorParameterGroup pdpSimulatorParameterGroup) {
81
82         topicSinks = TopicEndpointManager.getManager()
83                         .addTopicSinks(pdpSimulatorParameterGroup.getTopicParameterGroup().getTopicSinks());
84         topicSources = TopicEndpointManager.getManager()
85                         .addTopicSources(pdpSimulatorParameterGroup.getTopicParameterGroup().getTopicSources());
86
87         final int random = RANDOM.nextInt();
88         final String instanceId = "pdp_" + random;
89         LOGGER.debug("PdpSimulatorActivator initializing with instance id: {}", instanceId);
90         try {
91             this.pdpSimulatorParameterGroup = pdpSimulatorParameterGroup;
92             this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
93         } catch (final RuntimeException e) {
94             throw new PdpSimulatorRunTimeException(e);
95         }
96
97         final PdpUpdateListener pdpUpdateListener = new PdpUpdateListener();
98         final PdpStateChangeListener pdpStateChangeListener = new PdpStateChangeListener();
99         // @formatter:off
100         this.manager = new ServiceManager()
101             .addAction("topics",
102                 TopicEndpointManager.getManager()::start,
103                 TopicEndpointManager.getManager()::shutdown)
104             .addAction("set alive",
105                 () -> setAlive(true),
106                 () -> setAlive(false))
107             .addAction("register pdp status context object",
108                 () -> Registry.register(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT,
109                         new PdpMessageHandler().createPdpStatusFromParameters(instanceId,
110                                 pdpSimulatorParameterGroup.getPdpStatusParameters())),
111                 () -> Registry.unregister(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT))
112             .addAction("topic sinks",
113                 () -> Registry.register(PdpSimulatorConstants.REG_PDP_TOPIC_SINKS, topicSinks),
114                 () -> Registry.unregister(PdpSimulatorConstants.REG_PDP_TOPIC_SINKS))
115             .addAction("Pdp Status publisher",
116                 () -> Registry.register(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER,
117                         new PdpStatusPublisher(topicSinks,
118                                 pdpSimulatorParameterGroup.getPdpStatusParameters().getTimeIntervalMs())),
119                 this::stopAndRemovePdpStatusPublisher)
120             .addAction("Register pdp update listener",
121                 () -> msgDispatcher.register(PdpMessageType.PDP_UPDATE.name(), pdpUpdateListener),
122                 () -> msgDispatcher.unregister(PdpMessageType.PDP_UPDATE.name()))
123             .addAction("Register pdp state change request dispatcher",
124                 () -> msgDispatcher.register(PdpMessageType.PDP_STATE_CHANGE.name(), pdpStateChangeListener),
125                 () -> msgDispatcher.unregister(PdpMessageType.PDP_STATE_CHANGE.name()))
126             .addAction("Message Dispatcher",
127                 this::registerMsgDispatcher,
128                 this::unregisterMsgDispatcher);
129
130         // @formatter:on
131     }
132
133     /**
134      * Method to stop and unregister the pdp status publisher.
135      */
136     private void stopAndRemovePdpStatusPublisher() {
137         final PdpStatusPublisher pdpStatusPublisher =
138                 Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class);
139         pdpStatusPublisher.terminate();
140         Registry.unregister(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER);
141     }
142
143     /**
144      * Initialize PdpSimulator service.
145      *
146      * @throws PdpSimulatorException on errors in initializing the service
147      */
148     public void initialize() throws PdpSimulatorException {
149         if (isAlive()) {
150             throw new IllegalStateException("activator already initialized");
151         }
152
153         try {
154             LOGGER.debug("PdpSimulator starting as a service . . .");
155             manager.start();
156             LOGGER.debug("PdpSimulator started as a service");
157         } catch (final ServiceManagerException exp) {
158             LOGGER.error("PdpSimulator service startup failed");
159             throw new PdpSimulatorException(exp.getMessage(), exp);
160         }
161     }
162
163     /**
164      * Terminate PdpSimulator.
165      *
166      * @throws PdpSimulatorException on errors in terminating the service
167      */
168     public void terminate() throws PdpSimulatorException {
169         if (!isAlive()) {
170             throw new IllegalStateException("activator is not running");
171         }
172         try {
173             final PdpStatusPublisher pdpStatusPublisher =
174                     Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class);
175             // send a final heartbeat with terminated status
176             pdpStatusPublisher.send(new PdpMessageHandler().getTerminatedPdpStatus());
177             manager.stop();
178             Registry.unregister(PdpSimulatorConstants.REG_PDP_SIMULATOR_ACTIVATOR);
179         } catch (final ServiceManagerException exp) {
180             LOGGER.error("PdpSimulator termination failed");
181             throw new PdpSimulatorException(exp.getMessage(), exp);
182         }
183     }
184
185     /**
186      * Get the parameters used by the activator.
187      *
188      * @return pdpSimulatorParameterGroup the parameters of the activator
189      */
190     public PdpSimulatorParameterGroup getParameterGroup() {
191         return pdpSimulatorParameterGroup;
192     }
193
194     /**
195      * Registers the dispatcher with the topic source(s).
196      */
197     private void registerMsgDispatcher() {
198         for (final TopicSource source : topicSources) {
199             source.register(msgDispatcher);
200         }
201     }
202
203     /**
204      * Unregisters the dispatcher from the topic source(s).
205      */
206     private void unregisterMsgDispatcher() {
207         for (final TopicSource source : topicSources) {
208             source.unregister(msgDispatcher);
209         }
210     }
211 }