97feba152638f1a5159add4e3ab9406904d61ff8
[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.time.Instant;
25 import java.util.ArrayList;
26 import java.util.List;
27 import lombok.NonNull;
28 import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel;
29 import org.onap.policy.apex.model.enginemodel.concepts.AxEngineState;
30 import org.onap.policy.apex.service.engine.main.ApexPolicyStatisticsManager;
31 import org.onap.policy.apex.services.onappf.ApexStarterConstants;
32 import org.onap.policy.apex.services.onappf.parameters.PdpStatusParameters;
33 import org.onap.policy.apex.services.onappf.parameters.ToscaPolicyTypeIdentifierParameters;
34 import org.onap.policy.common.utils.services.Registry;
35 import org.onap.policy.models.pdp.concepts.PdpEngineWorkerStatistics;
36 import org.onap.policy.models.pdp.concepts.PdpResponseDetails;
37 import org.onap.policy.models.pdp.concepts.PdpStatistics;
38 import org.onap.policy.models.pdp.concepts.PdpStatus;
39 import org.onap.policy.models.pdp.enums.PdpEngineWorkerState;
40 import org.onap.policy.models.pdp.enums.PdpHealthStatus;
41 import org.onap.policy.models.pdp.enums.PdpResponseStatus;
42 import org.onap.policy.models.pdp.enums.PdpState;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
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 var 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<ToscaConceptIdentifier> getSupportedPolicyTypesFromParameters(
84             final PdpStatusParameters pdpStatusParameters) {
85         final List<ToscaConceptIdentifier> supportedPolicyTypes =
86                 new ArrayList<>(pdpStatusParameters.getSupportedPolicyTypes().size());
87         for (final ToscaPolicyTypeIdentifierParameters policyTypeIdentParameters : pdpStatusParameters
88                 .getSupportedPolicyTypes()) {
89             supportedPolicyTypes.add(new ToscaConceptIdentifier(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 var pdpStatusContext = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class);
102         final var 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         var pdpStatistics = new PdpStatistics();
133         pdpStatistics.setPdpInstanceId(pdpStatusContext.getName());
134         pdpStatistics.setTimeStamp(Instant.now());
135         pdpStatistics.setPdpGroupName(pdpStatusContext.getPdpGroup());
136         pdpStatistics.setPdpSubGroupName(pdpStatusContext.getPdpSubgroup());
137         if (apexEngineHandler != null) {
138             pdpStatistics.setEngineStats(getEngineWorkerStats(apexEngineHandler));
139         }
140         final var apexPolicyCounter = ApexPolicyStatisticsManager.getInstanceFromRegistry();
141         if (apexPolicyCounter != null) {
142             pdpStatistics.setPolicyDeploySuccessCount(apexPolicyCounter.getPolicyDeploySuccessCount());
143             pdpStatistics.setPolicyDeployFailCount(apexPolicyCounter.getPolicyDeployFailCount());
144             pdpStatistics.setPolicyDeployCount(apexPolicyCounter.getPolicyDeployCount());
145
146             pdpStatistics.setPolicyUndeploySuccessCount(apexPolicyCounter.getPolicyUndeploySuccessCount());
147             pdpStatistics.setPolicyUndeployFailCount(apexPolicyCounter.getPolicyUndeployFailCount());
148             pdpStatistics.setPolicyUndeployCount(apexPolicyCounter.getPolicyUndeployCount());
149
150             pdpStatistics.setPolicyExecutedCount(apexPolicyCounter.getPolicyExecutedCount());
151             pdpStatistics.setPolicyExecutedSuccessCount(apexPolicyCounter.getPolicyExecutedSuccessCount());
152             pdpStatistics.setPolicyExecutedFailCount(apexPolicyCounter.getPolicyExecutedFailCount());
153         }
154         return pdpStatistics;
155     }
156
157     private List<PdpEngineWorkerStatistics> getEngineWorkerStats(@NonNull final ApexEngineHandler apexEngineHandler) {
158         List<PdpEngineWorkerStatistics> pdpEngineWorkerStats = new ArrayList<>();
159         List<AxEngineModel> engineModels = apexEngineHandler.getEngineStats();
160         if (engineModels != null) {
161             engineModels.forEach(engineModel -> {
162                 var workerStatistics = new PdpEngineWorkerStatistics();
163                 workerStatistics.setEngineWorkerState(transferEngineState(engineModel.getState()));
164                 workerStatistics.setEngineId(engineModel.getId());
165                 workerStatistics.setEventCount(engineModel.getStats().getEventCount());
166                 workerStatistics.setAverageExecutionTime(engineModel.getStats().getAverageExecutionTime());
167                 workerStatistics.setEngineTimeStamp(engineModel.getStats().getTimeStamp());
168                 workerStatistics.setLastEnterTime(engineModel.getStats().getLastEnterTime());
169                 workerStatistics.setLastExecutionTime(engineModel.getStats().getLastExecutionTime());
170                 workerStatistics.setLastStart(engineModel.getStats().getLastStart());
171                 workerStatistics.setUpTime(engineModel.getStats().getUpTime());
172                 pdpEngineWorkerStats.add(workerStatistics);
173             });
174         }
175         return pdpEngineWorkerStats;
176     }
177
178     private PdpEngineWorkerState transferEngineState(@NonNull final AxEngineState state) {
179         switch (state) {
180             case STOPPING:
181                 return PdpEngineWorkerState.STOPPING;
182             case STOPPED:
183                 return PdpEngineWorkerState.STOPPED;
184             case READY:
185                 return PdpEngineWorkerState.READY;
186             case EXECUTING:
187                 return PdpEngineWorkerState.EXECUTING;
188             default:
189                 return PdpEngineWorkerState.UNDEFINED;
190         }
191     }
192
193     /**
194      * Method to get a final pdp status when the apex started is shutting down.
195      *
196      * @return PdpStatus the pdp status message
197      */
198     public PdpStatus getTerminatedPdpStatus() {
199         final var pdpStatusInContext = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class);
200         pdpStatusInContext.setState(PdpState.TERMINATED);
201         pdpStatusInContext.setDescription("Apex pdp shutting down.");
202         return createPdpStatusFromContext();
203     }
204
205     /**
206      * Method create PdpResponseDetails which will be sent as part of pdp status to PAP.
207      *
208      * @param requestId request id of the PdpUpdate message from pap
209      * @param status response status to be sent back
210      * @param responseMessage response message to be sent back
211      *
212      * @return PdpResponseDetails
213      */
214     public PdpResponseDetails createPdpResonseDetails(final String requestId, final PdpResponseStatus status,
215             final String responseMessage) {
216         final var pdpResponseDetails = new PdpResponseDetails();
217         pdpResponseDetails.setResponseTo(requestId);
218         pdpResponseDetails.setResponseStatus(status);
219         pdpResponseDetails.setResponseMessage(responseMessage);
220         return pdpResponseDetails;
221     }
222
223     /**
224      * Method to retrieve list of ToscaPolicyIdentifier from the list of ToscaPolicy.
225      *
226      * @param policies list of ToscaPolicy
227      *
228      * @return policyTypeIdentifiers
229      */
230     public List<ToscaConceptIdentifier> getToscaPolicyIdentifiers(final List<ToscaPolicy> policies) {
231         final List<ToscaConceptIdentifier> policyIdentifiers = new ArrayList<>(policies.size());
232         for (final ToscaPolicy policy : policies) {
233             if (null != policy.getName() && null != policy.getVersion()) {
234                 policyIdentifiers.add(new ToscaConceptIdentifier(policy.getName(), policy.getVersion()));
235             }
236         }
237         return policyIdentifiers;
238     }
239 }