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