968c54d3df450836ce92328d63475f865318c493
[policy/apex-pdp.git] /
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.apex.services.onappf;
23
24 import java.util.List;
25 import java.util.Properties;
26 import lombok.Getter;
27 import lombok.Setter;
28 import org.onap.policy.apex.services.onappf.comm.PdpStateChangeListener;
29 import org.onap.policy.apex.services.onappf.comm.PdpStatusPublisher;
30 import org.onap.policy.apex.services.onappf.comm.PdpUpdateListener;
31 import org.onap.policy.apex.services.onappf.exception.ApexStarterException;
32 import org.onap.policy.apex.services.onappf.exception.ApexStarterRunTimeException;
33 import org.onap.policy.apex.services.onappf.handler.PdpMessageHandler;
34 import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterGroup;
35 import org.onap.policy.apex.services.onappf.rest.ApexStarterRestServer;
36 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
37 import org.onap.policy.common.endpoints.event.comm.TopicSink;
38 import org.onap.policy.common.endpoints.event.comm.TopicSource;
39 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
40 import org.onap.policy.common.utils.services.Registry;
41 import org.onap.policy.common.utils.services.ServiceManager;
42 import org.onap.policy.common.utils.services.ServiceManagerException;
43 import org.onap.policy.models.pdp.enums.PdpMessageType;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * This class activates the ApexStarter as a complete service together with all its handlers.
49  *
50  * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
51  */
52 public class ApexStarterActivator {
53
54     private static final Logger LOGGER = LoggerFactory.getLogger(ApexStarterActivator.class);
55     private final ApexStarterParameterGroup apexStarterParameterGroup;
56     private List<TopicSink> topicSinks;// topics to which apex-pdp sends pdp status
57     private List<TopicSource> topicSources; // topics to which apex-pdp listens to for messages from pap.
58     private static final String[] MSG_TYPE_NAMES = { "messageName" };
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      * The ApexStarter REST API server.
72      */
73     private ApexStarterRestServer restServer;
74
75     @Getter
76     @Setter(lombok.AccessLevel.PRIVATE)
77     private volatile boolean alive = false;
78
79     /**
80      * Instantiate the activator for onappf PDP-A.
81      *
82      * @param apexStarterParameterGroup the parameters for the onappf PDP-A service
83      * @param topicProperties properties used to configure the topics
84      */
85     public ApexStarterActivator(final ApexStarterParameterGroup apexStarterParameterGroup,
86             final Properties topicProperties) {
87
88         topicSinks = TopicEndpointManager.getManager().addTopicSinks(topicProperties);
89         topicSources = TopicEndpointManager.getManager().addTopicSources(topicProperties);
90
91         // TODO: instanceId currently set as a random string, could be fetched from actual deployment
92         final int random = (int) (Math.random() * 100);
93         final String instanceId = "apex_" + random;
94         LOGGER.debug("ApexStarterActivator initializing with instance id:" + instanceId);
95         try {
96             this.apexStarterParameterGroup = apexStarterParameterGroup;
97             this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
98         } catch (final RuntimeException e) {
99             throw new ApexStarterRunTimeException(e);
100         }
101
102         final PdpUpdateListener pdpUpdateListener = new PdpUpdateListener();
103         final PdpStateChangeListener pdpStateChangeListener = new PdpStateChangeListener();
104         // @formatter:off
105         this.manager = new ServiceManager()
106                 .addAction("topics",
107                     () -> TopicEndpointManager.getManager().start(),
108                     () -> TopicEndpointManager.getManager().shutdown())
109                 .addAction("set alive",
110                     () -> setAlive(true),
111                     () -> setAlive(false))
112                 .addAction("register pdp status context object",
113                     () -> Registry.register(ApexStarterConstants.REG_PDP_STATUS_OBJECT,
114                                 new PdpMessageHandler().createPdpStatusFromParameters(instanceId,
115                                         apexStarterParameterGroup.getPdpStatusParameters())),
116                     () -> Registry.unregister(ApexStarterConstants.REG_PDP_STATUS_OBJECT))
117                 .addAction("topic sinks",
118                     () -> Registry.register(ApexStarterConstants.REG_APEX_PDP_TOPIC_SINKS, topicSinks),
119                     () -> Registry.unregister(ApexStarterConstants.REG_APEX_PDP_TOPIC_SINKS))
120                 .addAction("Pdp Status publisher",
121                     () -> Registry.register(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER,
122                                 new PdpStatusPublisher(topicSinks,
123                                         apexStarterParameterGroup.getPdpStatusParameters().getTimeIntervalMs())),
124                     () -> stopAndRemovePdpStatusPublisher())
125                 .addAction("Register pdp update listener",
126                     () -> msgDispatcher.register(PdpMessageType.PDP_UPDATE.name(), pdpUpdateListener),
127                     () -> msgDispatcher.unregister(PdpMessageType.PDP_UPDATE.name()))
128                 .addAction("Register pdp state change request dispatcher",
129                     () -> msgDispatcher.register(PdpMessageType.PDP_STATE_CHANGE.name(), pdpStateChangeListener),
130                     () -> msgDispatcher.unregister(PdpMessageType.PDP_STATE_CHANGE.name()))
131                 .addAction("Message Dispatcher",
132                     () -> registerMsgDispatcher(),
133                     () -> unregisterMsgDispatcher())
134                 .addAction("Create REST server",
135                     () -> restServer =
136                                     new ApexStarterRestServer(apexStarterParameterGroup.getRestServerParameters()),
137                     () -> restServer = null)
138                 .addAction("Rest Server",
139                     () -> restServer.start(),
140                     () -> restServer.stop());
141
142         // @formatter:on
143     }
144
145     /**
146      * Method to stop and unregister the pdp status publisher.
147      */
148     private void stopAndRemovePdpStatusPublisher() {
149         final PdpStatusPublisher pdpStatusPublisher =
150                 Registry.get(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class);
151         pdpStatusPublisher.terminate();
152         Registry.unregister(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER);
153     }
154
155     /**
156      * Initialize ApexStarter service.
157      *
158      * @throws ApexStarterException on errors in initializing the service
159      */
160     public void initialize() throws ApexStarterException {
161         if (isAlive()) {
162             throw new IllegalStateException("activator already initialized");
163         }
164
165         try {
166             LOGGER.debug("ApexStarter starting as a service . . .");
167             manager.start();
168             LOGGER.debug("ApexStarter started as a service");
169         } catch (final ServiceManagerException exp) {
170             LOGGER.error("ApexStarter service startup failed");
171             throw new ApexStarterException(exp.getMessage(), exp);
172         }
173     }
174
175     /**
176      * Terminate ApexStarter.
177      *
178      * @throws ApexStarterException on errors in terminating the service
179      */
180     public void terminate() throws ApexStarterException {
181         if (!isAlive()) {
182             throw new IllegalStateException("activator is not running");
183         }
184         try {
185             final PdpStatusPublisher pdpStatusPublisher =
186                     Registry.get(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class);
187             // send a final heartbeat with terminated status
188             pdpStatusPublisher.send(new PdpMessageHandler().getTerminatedPdpStatus());
189             manager.stop();
190             Registry.unregister(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR);
191         } catch (final ServiceManagerException exp) {
192             LOGGER.error("ApexStarter termination failed");
193             throw new ApexStarterException(exp.getMessage(), exp);
194         }
195     }
196
197     /**
198      * Get the parameters used by the activator.
199      *
200      * @return apexStarterParameterGroup the parameters of the activator
201      */
202     public ApexStarterParameterGroup getParameterGroup() {
203         return apexStarterParameterGroup;
204     }
205
206     /**
207      * Registers the dispatcher with the topic source(s).
208      */
209     private void registerMsgDispatcher() {
210         for (final TopicSource source : topicSources) {
211             source.register(msgDispatcher);
212         }
213     }
214
215     /**
216      * Unregisters the dispatcher from the topic source(s).
217      */
218     private void unregisterMsgDispatcher() {
219         for (final TopicSource source : topicSources) {
220             source.unregister(msgDispatcher);
221         }
222     }
223 }