Populate the PdpStatistics data in heartbeat
[policy/apex-pdp.git] / services / services-onappf / src / main / java / org / onap / policy / apex / services / onappf / handler / PdpMessageHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019-2020 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.services.onappf.handler;
22
23 import java.util.ArrayList;
24 import java.util.Date;
25 import java.util.List;
26 import lombok.NonNull;
27 import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel;
28 import org.onap.policy.apex.model.enginemodel.concepts.AxEngineState;
29 import org.onap.policy.apex.service.engine.main.ApexPolicyStatisticsManager;
30 import org.onap.policy.apex.services.onappf.ApexStarterConstants;
31 import org.onap.policy.apex.services.onappf.parameters.PdpStatusParameters;
32 import org.onap.policy.apex.services.onappf.parameters.ToscaPolicyTypeIdentifierParameters;
33 import org.onap.policy.common.utils.services.Registry;
34 import org.onap.policy.models.pdp.concepts.PdpEngineWorkerStatistics;
35 import org.onap.policy.models.pdp.concepts.PdpResponseDetails;
36 import org.onap.policy.models.pdp.concepts.PdpStatistics;
37 import org.onap.policy.models.pdp.concepts.PdpStatus;
38 import org.onap.policy.models.pdp.enums.PdpEngineWorkerState;
39 import org.onap.policy.models.pdp.enums.PdpHealthStatus;
40 import org.onap.policy.models.pdp.enums.PdpResponseStatus;
41 import org.onap.policy.models.pdp.enums.PdpState;
42 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48
49 /**
50  * This class supports the handling of pdp messages.
51  *
52  * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
53  */
54 public class PdpMessageHandler {
55     private static final Logger LOGGER = LoggerFactory.getLogger(PdpMessageHandler.class);
56
57     /**
58      * Method to create PdpStatus message from the parameters which will be saved to the context.
59      *
60      * @param instanceId instance id of apex pdp
61      * @param pdpStatusParameters pdp status parameters read from the configuration file
62      *
63      * @return pdpStatus the pdp status message
64      */
65     public PdpStatus createPdpStatusFromParameters(final String instanceId,
66             final PdpStatusParameters pdpStatusParameters) {
67         final PdpStatus pdpStatus = new PdpStatus();
68         pdpStatus.setPdpGroup(pdpStatusParameters.getPdpGroup());
69         pdpStatus.setPdpType(pdpStatusParameters.getPdpType());
70         pdpStatus.setState(PdpState.PASSIVE);
71         pdpStatus.setHealthy(PdpHealthStatus.HEALTHY);
72         pdpStatus.setDescription(pdpStatusParameters.getDescription());
73         pdpStatus.setName(instanceId);
74         return pdpStatus;
75     }
76
77     /**
78      * Method to get supported policy types from the parameters.
79      *
80      * @param pdpStatusParameters pdp status parameters
81      * @return supportedPolicyTypes list of PolicyTypeIdent
82      */
83     public List<ToscaPolicyTypeIdentifier> getSupportedPolicyTypesFromParameters(
84             final PdpStatusParameters pdpStatusParameters) {
85         final List<ToscaPolicyTypeIdentifier> supportedPolicyTypes =
86                 new ArrayList<>(pdpStatusParameters.getSupportedPolicyTypes().size());
87         for (final ToscaPolicyTypeIdentifierParameters policyTypeIdentParameters : pdpStatusParameters
88                 .getSupportedPolicyTypes()) {
89             supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier(policyTypeIdentParameters.getName(),
90                     policyTypeIdentParameters.getVersion()));
91         }
92         return supportedPolicyTypes;
93     }
94
95     /**
96      * Method to create PdpStatus message from the context, which is to be sent by apex-pdp to pap.
97      *
98      * @return PdpStatus the pdp status message
99      */
100     public PdpStatus createPdpStatusFromContext() {
101         final PdpStatus pdpStatusContext = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class);
102         final PdpStatus pdpStatus = new PdpStatus();
103         pdpStatus.setName(pdpStatusContext.getName());
104         pdpStatus.setPdpType(pdpStatusContext.getPdpType());
105         pdpStatus.setState(pdpStatusContext.getState());
106         pdpStatus.setHealthy(pdpStatusContext.getHealthy());
107         pdpStatus.setDescription(pdpStatusContext.getDescription());
108         pdpStatus.setPolicies(pdpStatusContext.getPolicies());
109         pdpStatus.setPdpGroup(pdpStatusContext.getPdpGroup());
110         pdpStatus.setPdpSubgroup(pdpStatusContext.getPdpSubgroup());
111
112         ApexEngineHandler apexEngineHandler = null;
113         try {
114             apexEngineHandler = Registry.get(ApexStarterConstants.REG_APEX_ENGINE_HANDLER);
115         } catch (IllegalArgumentException e) {
116             LOGGER.warn(e.getMessage());
117         }
118
119         pdpStatus.setStatistics(getStatistics(pdpStatus, apexEngineHandler));
120
121
122         return pdpStatus;
123     }
124
125     /**
126      * Method to get the statistics.
127      *
128      * @return PdpStatistics the pdp status message
129      */
130
131     private PdpStatistics getStatistics(final PdpStatus pdpStatusContext, final ApexEngineHandler apexEngineHandler) {
132         PdpStatistics pdpStatistics = new PdpStatistics();
133         pdpStatistics.setPdpInstanceId(pdpStatusContext.getName());
134         pdpStatistics.setTimeStamp(new Date());
135         pdpStatistics.setPdpGroupName(pdpStatusContext.getPdpGroup());
136         pdpStatistics.setPdpSubGroupName(pdpStatusContext.getPdpSubgroup());
137         if (apexEngineHandler != null) {
138             pdpStatistics.setEngineStats(getEngineWorkerStats(apexEngineHandler));
139         }
140         final ApexPolicyStatisticsManager apexPolicyCounter = ApexPolicyStatisticsManager.getInstanceFromRegistry();
141         if (apexPolicyCounter != null) {
142             pdpStatistics.setPolicyDeploySuccessCount(apexPolicyCounter.getPolicyDeploySuccessCount());
143             pdpStatistics.setPolicyDeployFailCount(apexPolicyCounter.getPolicyDeployFailCount());
144             pdpStatistics.setPolicyDeployCount(apexPolicyCounter.getPolicyDeployCount());
145             pdpStatistics.setPolicyExecutedCount(apexPolicyCounter.getPolicyExecutedCount());
146             pdpStatistics.setPolicyExecutedSuccessCount(apexPolicyCounter.getPolicyExecutedSuccessCount());
147             pdpStatistics.setPolicyExecutedFailCount(apexPolicyCounter.getPolicyExecutedFailCount());
148         }
149         return pdpStatistics;
150     }
151
152     private List<PdpEngineWorkerStatistics> getEngineWorkerStats(@NonNull final ApexEngineHandler apexEngineHandler) {
153         List<PdpEngineWorkerStatistics> pdpEngineWorkerStats = new ArrayList<>();
154         List<AxEngineModel> engineModels = apexEngineHandler.getEngineStats();
155         if (engineModels != null) {
156             engineModels.forEach(engineModel -> {
157                 PdpEngineWorkerStatistics workerStatistics = new PdpEngineWorkerStatistics();
158                 workerStatistics.setEngineWorkerState(transferEngineState(engineModel.getState()));
159                 workerStatistics.setEngineId(engineModel.getId());
160                 workerStatistics.setEventCount(engineModel.getStats().getEventCount());
161                 workerStatistics.setAverageExecutionTime(engineModel.getStats().getAverageExecutionTime());
162                 workerStatistics.setEngineTimeStamp(engineModel.getStats().getTimeStamp());
163                 workerStatistics.setLastEnterTime(engineModel.getStats().getLastEnterTime());
164                 workerStatistics.setLastExecutionTime(engineModel.getStats().getLastExecutionTime());
165                 workerStatistics.setLastStart(engineModel.getStats().getLastStart());
166                 workerStatistics.setUpTime(engineModel.getStats().getUpTime());
167                 pdpEngineWorkerStats.add(workerStatistics);
168             });
169         }
170         return pdpEngineWorkerStats;
171     }
172
173     private PdpEngineWorkerState transferEngineState(@NonNull final AxEngineState state) {
174         switch (state) {
175             case STOPPING:
176                 return PdpEngineWorkerState.STOPPING;
177             case STOPPED:
178                 return PdpEngineWorkerState.STOPPED;
179             case READY:
180                 return PdpEngineWorkerState.READY;
181             case EXECUTING:
182                 return PdpEngineWorkerState.EXECUTING;
183             default:
184                 return PdpEngineWorkerState.UNDEFINED;
185         }
186     }
187
188     /**
189      * Method to get a final pdp status when the apex started is shutting down.
190      *
191      * @return PdpStatus the pdp status message
192      */
193     public PdpStatus getTerminatedPdpStatus() {
194         final PdpStatus pdpStatusInContext = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class);
195         pdpStatusInContext.setState(PdpState.TERMINATED);
196         pdpStatusInContext.setDescription("Apex pdp shutting down.");
197         return createPdpStatusFromContext();
198     }
199
200     /**
201      * Method create PdpResponseDetails which will be sent as part of pdp status to PAP.
202      *
203      * @param requestId request id of the PdpUpdate message from pap
204      * @param status response status to be sent back
205      * @param responseMessage response message to be sent back
206      *
207      * @return PdpResponseDetails
208      */
209     public PdpResponseDetails createPdpResonseDetails(final String requestId, final PdpResponseStatus status,
210             final String responseMessage) {
211         final PdpResponseDetails pdpResponseDetails = new PdpResponseDetails();
212         pdpResponseDetails.setResponseTo(requestId);
213         pdpResponseDetails.setResponseStatus(status);
214         pdpResponseDetails.setResponseMessage(responseMessage);
215         return pdpResponseDetails;
216     }
217
218     /**
219      * Method to retrieve list of ToscaPolicyIdentifier from the list of ToscaPolicy.
220      *
221      * @param policies list of ToscaPolicy
222      *
223      * @return policyTypeIdentifiers
224      */
225     public List<ToscaPolicyIdentifier> getToscaPolicyIdentifiers(final List<ToscaPolicy> policies) {
226         final List<ToscaPolicyIdentifier> policyIdentifiers = new ArrayList<>(policies.size());
227         for (final ToscaPolicy policy : policies) {
228             if (null != policy.getName() && null != policy.getVersion()) {
229                 policyIdentifiers.add(new ToscaPolicyIdentifier(policy.getName(), policy.getVersion()));
230             }
231         }
232         return policyIdentifiers;
233     }
234 }