ec2f5b34a7859417b7021c140bf8d3e5351369d5
[policy/apex-pdp.git] / services / services-onappf / src / main / java / org / onap / policy / apex / services / onappf / ApexStarterActivator.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.apex.services.onappf;
23
24 import java.util.List;
25 import lombok.Getter;
26 import lombok.Setter;
27 import org.onap.policy.apex.services.onappf.comm.PdpStateChangeListener;
28 import org.onap.policy.apex.services.onappf.comm.PdpStatusPublisher;
29 import org.onap.policy.apex.services.onappf.comm.PdpUpdateListener;
30 import org.onap.policy.apex.services.onappf.exception.ApexStarterException;
31 import org.onap.policy.apex.services.onappf.exception.ApexStarterRunTimeException;
32 import org.onap.policy.apex.services.onappf.handler.PdpMessageHandler;
33 import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterGroup;
34 import org.onap.policy.apex.services.onappf.rest.ApexStarterRestServer;
35 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
36 import org.onap.policy.common.endpoints.event.comm.TopicSink;
37 import org.onap.policy.common.endpoints.event.comm.TopicSource;
38 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
39 import org.onap.policy.common.utils.network.NetworkUtil;
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.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
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     @Getter
81     private List<ToscaPolicyTypeIdentifier> supportedPolicyTypes;
82
83     /**
84      * Instantiate the activator for onappf PDP-A.
85      *
86      * @param apexStarterParameterGroup the parameters for the onappf PDP-A service
87      */
88     public ApexStarterActivator(final ApexStarterParameterGroup apexStarterParameterGroup) {
89
90         topicSinks = TopicEndpointManager.getManager()
91                         .addTopicSinks(apexStarterParameterGroup.getTopicParameterGroup().getTopicSinks());
92
93         topicSources = TopicEndpointManager.getManager()
94                         .addTopicSources(apexStarterParameterGroup.getTopicParameterGroup().getTopicSources());
95
96         final String instanceId = NetworkUtil.getHostname();
97         LOGGER.debug("ApexStarterActivator initializing with instance id: {}", instanceId);
98         try {
99             this.apexStarterParameterGroup = apexStarterParameterGroup;
100             this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
101         } catch (final RuntimeException e) {
102             throw new ApexStarterRunTimeException(e);
103         }
104
105         final PdpUpdateListener pdpUpdateListener = new PdpUpdateListener();
106         final PdpStateChangeListener pdpStateChangeListener = new PdpStateChangeListener();
107         final PdpMessageHandler pdpMessageHandler = new PdpMessageHandler();
108         supportedPolicyTypes =
109             pdpMessageHandler.getSupportedPolicyTypesFromParameters(apexStarterParameterGroup.getPdpStatusParameters());
110
111         // @formatter:off
112         this.manager = new ServiceManager()
113                 .addAction("topics",
114                     () -> TopicEndpointManager.getManager().start(),
115                     () -> TopicEndpointManager.getManager().shutdown())
116                 .addAction("set alive",
117                     () -> setAlive(true),
118                     () -> setAlive(false))
119                 .addAction("register pdp status context object",
120                     () -> Registry.register(ApexStarterConstants.REG_PDP_STATUS_OBJECT,
121                                 pdpMessageHandler.createPdpStatusFromParameters(instanceId,
122                                         apexStarterParameterGroup.getPdpStatusParameters())),
123                     () -> Registry.unregister(ApexStarterConstants.REG_PDP_STATUS_OBJECT))
124                 .addAction("topic sinks",
125                     () -> Registry.register(ApexStarterConstants.REG_APEX_PDP_TOPIC_SINKS, topicSinks),
126                     () -> Registry.unregister(ApexStarterConstants.REG_APEX_PDP_TOPIC_SINKS))
127                 .addAction("Pdp Status publisher",
128                     () -> Registry.register(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER,
129                                 new PdpStatusPublisher(topicSinks,
130                                         apexStarterParameterGroup.getPdpStatusParameters().getTimeIntervalMs())),
131                     () -> stopAndRemovePdpStatusPublisher())
132                 .addAction("Register pdp update listener",
133                     () -> msgDispatcher.register(PdpMessageType.PDP_UPDATE.name(), pdpUpdateListener),
134                     () -> msgDispatcher.unregister(PdpMessageType.PDP_UPDATE.name()))
135                 .addAction("Register pdp state change request dispatcher",
136                     () -> msgDispatcher.register(PdpMessageType.PDP_STATE_CHANGE.name(), pdpStateChangeListener),
137                     () -> msgDispatcher.unregister(PdpMessageType.PDP_STATE_CHANGE.name()))
138                 .addAction("Message Dispatcher",
139                     () -> registerMsgDispatcher(),
140                     () -> unregisterMsgDispatcher())
141                 .addAction("Create REST server",
142                     () -> restServer =
143                                     new ApexStarterRestServer(apexStarterParameterGroup.getRestServerParameters()),
144                     () -> restServer = null)
145                 .addAction("Rest Server",
146                     () -> restServer.start(),
147                     () -> restServer.stop());
148
149         // @formatter:on
150     }
151
152     /**
153      * Method to stop and unregister the pdp status publisher.
154      */
155     private void stopAndRemovePdpStatusPublisher() {
156         final PdpStatusPublisher pdpStatusPublisher =
157                 Registry.get(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class);
158         pdpStatusPublisher.terminate();
159         Registry.unregister(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER);
160     }
161
162     /**
163      * Initialize ApexStarter service.
164      *
165      * @throws ApexStarterException on errors in initializing the service
166      */
167     public void initialize() throws ApexStarterException {
168         if (isAlive()) {
169             throw new IllegalStateException("activator already initialized");
170         }
171
172         try {
173             LOGGER.debug("ApexStarter starting as a service . . .");
174             manager.start();
175             LOGGER.debug("ApexStarter started as a service");
176         } catch (final ServiceManagerException exp) {
177             LOGGER.error("ApexStarter service startup failed");
178             throw new ApexStarterException(exp.getMessage(), exp);
179         }
180     }
181
182     /**
183      * Terminate ApexStarter.
184      *
185      * @throws ApexStarterException on errors in terminating the service
186      */
187     public void terminate() throws ApexStarterException {
188         if (!isAlive()) {
189             throw new IllegalStateException("activator is not running");
190         }
191         try {
192             final PdpStatusPublisher pdpStatusPublisher =
193                     Registry.get(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class);
194             // send a final heartbeat with terminated status
195             pdpStatusPublisher.send(new PdpMessageHandler().getTerminatedPdpStatus());
196             manager.stop();
197             Registry.unregister(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR);
198         } catch (final ServiceManagerException exp) {
199             LOGGER.error("ApexStarter termination failed");
200             throw new ApexStarterException(exp.getMessage(), exp);
201         }
202     }
203
204     /**
205      * Get the parameters used by the activator.
206      *
207      * @return apexStarterParameterGroup the parameters of the activator
208      */
209     public ApexStarterParameterGroup getParameterGroup() {
210         return apexStarterParameterGroup;
211     }
212
213     /**
214      * Registers the dispatcher with the topic source(s).
215      */
216     private void registerMsgDispatcher() {
217         for (final TopicSource source : topicSources) {
218             source.register(msgDispatcher);
219         }
220     }
221
222     /**
223      * Unregisters the dispatcher from the topic source(s).
224      */
225     private void unregisterMsgDispatcher() {
226         for (final TopicSource source : topicSources) {
227             source.unregister(msgDispatcher);
228         }
229     }
230 }