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