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