e08b5b344658518c0cc17a7ed39069db5612b0cd
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.services.onappf;
22
23 import java.util.List;
24 import java.util.Properties;
25
26 import lombok.Getter;
27 import lombok.Setter;
28
29 import org.onap.policy.apex.services.onappf.comm.PdpStateChangeListener;
30 import org.onap.policy.apex.services.onappf.comm.PdpStatusPublisher;
31 import org.onap.policy.apex.services.onappf.comm.PdpUpdateListener;
32 import org.onap.policy.apex.services.onappf.exception.ApexStarterException;
33 import org.onap.policy.apex.services.onappf.exception.ApexStarterRunTimeException;
34 import org.onap.policy.apex.services.onappf.handler.PdpMessageHandler;
35 import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterGroup;
36 import org.onap.policy.apex.services.onappf.rest.ApexStarterRestServer;
37 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
38 import org.onap.policy.common.endpoints.event.comm.TopicSink;
39 import org.onap.policy.common.endpoints.event.comm.TopicSource;
40 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
41 import org.onap.policy.common.utils.services.Registry;
42 import org.onap.policy.common.utils.services.ServiceManager;
43 import org.onap.policy.common.utils.services.ServiceManagerException;
44 import org.onap.policy.models.pdp.enums.PdpMessageType;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * This class activates the ApexStarter as a complete service together with all its handlers.
50  *
51  * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
52  */
53 public class ApexStarterActivator {
54
55     private static final Logger LOGGER = LoggerFactory.getLogger(ApexStarterActivator.class);
56     private final ApexStarterParameterGroup apexStarterParameterGroup;
57     private List<TopicSink> topicSinks;// topics to which apex-pdp sends pdp status
58     private List<TopicSource> topicSources; // topics to which apex-pdp listens to for messages from pap.
59     private static final String[] MSG_TYPE_NAMES = { "messageName" };
60
61     /**
62      * Listens for messages on the topic, decodes them into a message, and then dispatches them.
63      */
64     private final MessageTypeDispatcher msgDispatcher;
65
66     /**
67      * Used to manage the services.
68      */
69     private ServiceManager manager;
70
71     /**
72      * The ApexStarter REST API server.
73      */
74     private ApexStarterRestServer restServer;
75
76     @Getter
77     @Setter(lombok.AccessLevel.PRIVATE)
78     private volatile boolean alive = false;
79
80     /**
81      * Instantiate the activator for onappf PDP-A.
82      *
83      * @param apexStarterParameterGroup the parameters for the onappf PDP-A service
84      * @param topicProperties properties used to configure the topics
85      */
86     public ApexStarterActivator(final ApexStarterParameterGroup apexStarterParameterGroup,
87             final Properties topicProperties) {
88
89         topicSinks = TopicEndpoint.manager.addTopicSinks(topicProperties);
90         topicSources = TopicEndpoint.manager.addTopicSources(topicProperties);
91
92         // TODO: instanceId currently set as a random string, could be fetched from actual deployment
93         final int random = (int) (Math.random() * 100);
94         final String instanceId = "apex_" + random;
95         LOGGER.debug("ApexStarterActivator initializing with instance id:" + instanceId);
96         try {
97             this.apexStarterParameterGroup = apexStarterParameterGroup;
98             this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
99         } catch (final RuntimeException e) {
100             throw new ApexStarterRunTimeException(e);
101         }
102
103         final PdpUpdateListener pdpUpdateListener = new PdpUpdateListener();
104         final PdpStateChangeListener pdpStateChangeListener = new PdpStateChangeListener();
105         // @formatter:off
106         this.manager = new ServiceManager()
107                 .addAction("topics",
108                         () -> TopicEndpoint.manager.start(),
109                         () -> TopicEndpoint.manager.shutdown())
110                 .addAction("set alive",
111                         () -> setAlive(true),
112                         () -> setAlive(false))
113                 .addAction("register pdp status context object",
114                         () -> Registry.register(ApexStarterConstants.REG_PDP_STATUS_OBJECT,
115                                 new PdpMessageHandler().createPdpStatusFromParameters(instanceId,
116                                         apexStarterParameterGroup.getPdpStatusParameters())),
117                         () -> Registry.unregister(ApexStarterConstants.REG_PDP_STATUS_OBJECT))
118                 .addAction("topic sinks",
119                         () -> Registry.register(ApexStarterConstants.REG_APEX_PDP_TOPIC_SINKS, topicSinks),
120                         () -> Registry.unregister(ApexStarterConstants.REG_APEX_PDP_TOPIC_SINKS))
121                 .addAction("Pdp Status publisher",
122                         () -> Registry.register(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER,
123                                 new PdpStatusPublisher(topicSinks,
124                                         apexStarterParameterGroup.getPdpStatusParameters().getTimeIntervalMs())),
125                         () -> stopAndRemovePdpStatusPublisher())
126                 .addAction("Register pdp update listener",
127                     () -> msgDispatcher.register(PdpMessageType.PDP_UPDATE.name(), pdpUpdateListener),
128                     () -> msgDispatcher.unregister(PdpMessageType.PDP_UPDATE.name()))
129                 .addAction("Register pdp state change request dispatcher",
130                         () -> msgDispatcher.register(PdpMessageType.PDP_STATE_CHANGE.name(), pdpStateChangeListener),
131                         () -> msgDispatcher.unregister(PdpMessageType.PDP_STATE_CHANGE.name()))
132                 .addAction("Message Dispatcher",
133                     () -> registerMsgDispatcher(),
134                     () -> unregisterMsgDispatcher())
135                 .addAction("Create REST server",
136                         () -> restServer =
137                                     new ApexStarterRestServer(apexStarterParameterGroup.getRestServerParameters()),
138                         () -> restServer = null)
139                 .addAction("Rest Server",
140                         () -> restServer.start(),
141                         () -> restServer.stop());
142
143         // @formatter:on
144     }
145
146     /**
147      * Method to stop and unregister the pdp status publisher.
148      */
149     private void stopAndRemovePdpStatusPublisher() {
150         final PdpStatusPublisher pdpStatusPublisher =
151                 Registry.get(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class);
152         pdpStatusPublisher.terminate();
153         Registry.unregister(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER);
154     }
155
156     /**
157      * Initialize ApexStarter service.
158      *
159      * @throws ApexStarterException on errors in initializing the service
160      */
161     public void initialize() throws ApexStarterException {
162         if (isAlive()) {
163             throw new IllegalStateException("activator already initialized");
164         }
165
166         try {
167             LOGGER.debug("ApexStarter starting as a service . . .");
168             manager.start();
169             LOGGER.debug("ApexStarter started as a service");
170         } catch (final ServiceManagerException exp) {
171             LOGGER.error("ApexStarter service startup failed");
172             throw new ApexStarterException(exp.getMessage(), exp);
173         }
174     }
175
176     /**
177      * Terminate ApexStarter.
178      *
179      * @throws ApexStarterException on errors in terminating the service
180      */
181     public void terminate() throws ApexStarterException {
182         if (!isAlive()) {
183             throw new IllegalStateException("activator is not running");
184         }
185         try {
186             final PdpStatusPublisher pdpStatusPublisher =
187                     Registry.get(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class);
188             // send a final heartbeat with terminated status
189             pdpStatusPublisher.send(new PdpMessageHandler().getTerminatedPdpStatus());
190             manager.stop();
191             Registry.unregister(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR);
192         } catch (final ServiceManagerException exp) {
193             LOGGER.error("ApexStarter termination failed");
194             throw new ApexStarterException(exp.getMessage(), exp);
195         }
196     }
197
198     /**
199      * Get the parameters used by the activator.
200      *
201      * @return apexStarterParameterGroup the parameters of the activator
202      */
203     public ApexStarterParameterGroup getParameterGroup() {
204         return apexStarterParameterGroup;
205     }
206
207     /**
208      * Registers the dispatcher with the topic source(s).
209      */
210     private void registerMsgDispatcher() {
211         for (final TopicSource source : topicSources) {
212             source.register(msgDispatcher);
213         }
214     }
215
216     /**
217      * Unregisters the dispatcher from the topic source(s).
218      */
219     private void unregisterMsgDispatcher() {
220         for (final TopicSource source : topicSources) {
221             source.unregister(msgDispatcher);
222         }
223     }
224 }