e6fd9e4773d7200dddff51cd1f7daee1ce312121
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019-2021 Nordix Foundation.
4  *  Modifications Copyright (C) 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.handler;
23
24 import java.util.HashSet;
25 import java.util.List;
26 import org.onap.policy.apex.service.engine.main.ApexPolicyStatisticsManager;
27 import org.onap.policy.apex.services.onappf.ApexStarterConstants;
28 import org.onap.policy.apex.services.onappf.comm.PdpStatusPublisher;
29 import org.onap.policy.apex.services.onappf.exception.ApexStarterException;
30 import org.onap.policy.common.utils.services.Registry;
31 import org.onap.policy.models.pdp.concepts.PdpResponseDetails;
32 import org.onap.policy.models.pdp.concepts.PdpStateChange;
33 import org.onap.policy.models.pdp.concepts.PdpStatus;
34 import org.onap.policy.models.pdp.enums.PdpResponseStatus;
35 import org.onap.policy.models.pdp.enums.PdpState;
36 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
37 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42  * This class supports the handling of pdp state change messages.
43  *
44  * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
45  */
46 public class PdpStateChangeMessageHandler {
47
48     private static final Logger LOGGER = LoggerFactory.getLogger(PdpStateChangeMessageHandler.class);
49
50     /**
51      * Method which handles a pdp state change event from PAP.
52      *
53      * @param pdpStateChangeMsg pdp state change message
54      */
55     public void handlePdpStateChangeEvent(final PdpStateChange pdpStateChangeMsg) {
56         final var pdpStatusContext = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class);
57         final var pdpStatusPublisher =
58                         Registry.get(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class);
59         final var pdpMessageHandler = new PdpMessageHandler();
60         PdpResponseDetails pdpResponseDetails = null;
61         if (pdpStateChangeMsg.appliesTo(pdpStatusContext.getName(), pdpStatusContext.getPdpGroup(),
62                 pdpStatusContext.getPdpSubgroup())) {
63             switch (pdpStateChangeMsg.getState()) {
64                 case PASSIVE:
65                     pdpResponseDetails = handlePassiveState(pdpStateChangeMsg, pdpStatusContext, pdpMessageHandler);
66                     break;
67                 case ACTIVE:
68                     pdpResponseDetails = handleActiveState(pdpStateChangeMsg, pdpStatusContext, pdpMessageHandler);
69                     break;
70                 default:
71                     break;
72             }
73             final var pdpStatus = pdpMessageHandler.createPdpStatusFromContext();
74             pdpStatus.setResponse(pdpResponseDetails);
75             pdpStatus.setDescription("Pdp status response message for PdpStateChange");
76             pdpStatusPublisher.send(pdpStatus);
77         }
78     }
79
80     /**
81      * Method to handle when the new state from pap is active.
82      *
83      * @param pdpStateChangeMsg pdp state change message
84      * @param pdpStatusContext pdp status object in memory
85      * @param pdpMessageHandler the pdp message handler
86      * @return pdpResponseDetails pdp response
87      */
88     private PdpResponseDetails handleActiveState(final PdpStateChange pdpStateChangeMsg,
89             final PdpStatus pdpStatusContext, final PdpMessageHandler pdpMessageHandler) {
90         PdpResponseDetails pdpResponseDetails = null;
91         if (pdpStatusContext.getState().equals(PdpState.ACTIVE)) {
92             pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(),
93                     PdpResponseStatus.SUCCESS, "Pdp already in active state");
94         } else {
95             final List<ToscaPolicy> policies = Registry.get(ApexStarterConstants.REG_APEX_TOSCA_POLICY_LIST);
96             if (policies.isEmpty()) {
97                 pdpStatusContext.setState(PdpState.ACTIVE);
98                 pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(),
99                         PdpResponseStatus.SUCCESS, "State changed to active. No policies found.");
100             } else {
101                 pdpResponseDetails = startApexEngine(pdpStateChangeMsg, pdpStatusContext, pdpMessageHandler, policies);
102             }
103         }
104         return pdpResponseDetails;
105     }
106
107     /**
108      * Method to start apex engine.
109      *
110      * @param pdpStateChangeMsg pdp state change message
111      * @param pdpStatusContext pdp status in memory
112      * @param pdpMessageHandler the pdp message handler
113      * @param policies list of policies
114      * @return pdp response details
115      */
116     private PdpResponseDetails startApexEngine(final PdpStateChange pdpStateChangeMsg, final PdpStatus pdpStatusContext,
117         final PdpMessageHandler pdpMessageHandler, final List<ToscaPolicy> policies) {
118         PdpResponseDetails pdpResponseDetails;
119         try {
120             final var apexEngineHandler = new ApexEngineHandler(policies);
121             Registry.registerOrReplace(ApexStarterConstants.REG_APEX_ENGINE_HANDLER, apexEngineHandler);
122             if (apexEngineHandler.isApexEngineRunning()) {
123                 List<ToscaConceptIdentifier> runningPolicies = apexEngineHandler.getRunningPolicies();
124                 // only the policies which are succesfully executed should be there in the heartbeat
125                 pdpStatusContext.setPolicies(runningPolicies);
126                 if (new HashSet<>(runningPolicies)
127                     .equals(new HashSet<>(pdpMessageHandler.getToscaPolicyIdentifiers(policies)))) {
128                     pdpResponseDetails =
129                         pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(),
130                             PdpResponseStatus.SUCCESS, "Apex engine started. State changed to active.");
131                 } else {
132                     var message = new StringBuilder(
133                         "Apex engine started. But, only the following polices are running - ");
134                     for (ToscaConceptIdentifier policy : runningPolicies) {
135                         message.append(policy.getName()).append(":").append(policy.getVersion()).append("  ");
136                     }
137                     message.append(". Other policies failed execution. Please see the logs for more details.");
138                     pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(
139                         pdpStateChangeMsg.getRequestId(), PdpResponseStatus.SUCCESS, message.toString());
140                 }
141                 pdpStatusContext.setState(PdpState.ACTIVE);
142             } else {
143                 pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(),
144                     PdpResponseStatus.FAIL, "Apex engine failed to start. State cannot be changed to active.");
145             }
146         } catch (final ApexStarterException e) {
147             LOGGER.error("Pdp State Change failed.", e);
148             pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(),
149                     PdpResponseStatus.FAIL, "Apex engine service running failed. " + e.getMessage());
150         }
151         final var apexPolicyStatisticsManager = ApexPolicyStatisticsManager.getInstanceFromRegistry();
152         if (apexPolicyStatisticsManager != null) {
153             apexPolicyStatisticsManager
154                     .updatePolicyDeployCounter(pdpResponseDetails.getResponseStatus() == PdpResponseStatus.SUCCESS);
155         }
156         return pdpResponseDetails;
157     }
158
159     /**
160      * Method to handle when the new state from pap is passive.
161      *
162      * @param pdpStateChangeMsg pdp state change message
163      * @param pdpStatusContext pdp status object in memory
164      * @param pdpMessageHandler the pdp message handler
165      * @return pdpResponseDetails pdp response
166      */
167     private PdpResponseDetails handlePassiveState(final PdpStateChange pdpStateChangeMsg,
168             final PdpStatus pdpStatusContext, final PdpMessageHandler pdpMessageHandler) {
169         PdpResponseDetails pdpResponseDetails = null;
170         if (pdpStatusContext.getState().equals(PdpState.PASSIVE)) {
171             pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(),
172                     PdpResponseStatus.SUCCESS, "Pdp already in passive state");
173         } else {
174             ApexEngineHandler apexEngineHandler = null;
175             try {
176                 apexEngineHandler = Registry.get(ApexStarterConstants.REG_APEX_ENGINE_HANDLER);
177             } catch (final IllegalArgumentException e) {
178                 LOGGER.debug("ApenEngineHandler not in registry.", e);
179             }
180             try {
181                 if (null != apexEngineHandler && apexEngineHandler.isApexEngineRunning()) {
182                     apexEngineHandler.shutdown();
183                 }
184                 pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(),
185                         PdpResponseStatus.SUCCESS, "Apex pdp state changed from Active to Passive.");
186                 pdpStatusContext.setState(PdpState.PASSIVE);
187             } catch (final Exception e) {
188                 LOGGER.error("Stopping apex engine failed. State cannot be changed to Passive.", e);
189                 pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(),
190                         PdpResponseStatus.FAIL,
191                         "Stopping apex engine failed. State cannot be changed to Passive." + e.getMessage());
192             }
193         }
194         return pdpResponseDetails;
195     }
196 }