aboutsummaryrefslogtreecommitdiffstats
path: root/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpMessageHandler.java
blob: 97feba152638f1a5159add4e3ab9406904d61ff8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019-2021 Nordix Foundation.
 *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.services.onappf.handler;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import lombok.NonNull;
import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel;
import org.onap.policy.apex.model.enginemodel.concepts.AxEngineState;
import org.onap.policy.apex.service.engine.main.ApexPolicyStatisticsManager;
import org.onap.policy.apex.services.onappf.ApexStarterConstants;
import org.onap.policy.apex.services.onappf.parameters.PdpStatusParameters;
import org.onap.policy.apex.services.onappf.parameters.ToscaPolicyTypeIdentifierParameters;
import org.onap.policy.common.utils.services.Registry;
import org.onap.policy.models.pdp.concepts.PdpEngineWorkerStatistics;
import org.onap.policy.models.pdp.concepts.PdpResponseDetails;
import org.onap.policy.models.pdp.concepts.PdpStatistics;
import org.onap.policy.models.pdp.concepts.PdpStatus;
import org.onap.policy.models.pdp.enums.PdpEngineWorkerState;
import org.onap.policy.models.pdp.enums.PdpHealthStatus;
import org.onap.policy.models.pdp.enums.PdpResponseStatus;
import org.onap.policy.models.pdp.enums.PdpState;
import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * This class supports the handling of pdp messages.
 *
 * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
 */
public class PdpMessageHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(PdpMessageHandler.class);

    /**
     * Method to create PdpStatus message from the parameters which will be saved to the context.
     *
     * @param instanceId instance id of apex pdp
     * @param pdpStatusParameters pdp status parameters read from the configuration file
     *
     * @return pdpStatus the pdp status message
     */
    public PdpStatus createPdpStatusFromParameters(final String instanceId,
            final PdpStatusParameters pdpStatusParameters) {
        final var pdpStatus = new PdpStatus();
        pdpStatus.setPdpGroup(pdpStatusParameters.getPdpGroup());
        pdpStatus.setPdpType(pdpStatusParameters.getPdpType());
        pdpStatus.setState(PdpState.PASSIVE);
        pdpStatus.setHealthy(PdpHealthStatus.HEALTHY);
        pdpStatus.setDescription(pdpStatusParameters.getDescription());
        pdpStatus.setName(instanceId);
        return pdpStatus;
    }

    /**
     * Method to get supported policy types from the parameters.
     *
     * @param pdpStatusParameters pdp status parameters
     * @return supportedPolicyTypes list of PolicyTypeIdent
     */
    public List<ToscaConceptIdentifier> getSupportedPolicyTypesFromParameters(
            final PdpStatusParameters pdpStatusParameters) {
        final List<ToscaConceptIdentifier> supportedPolicyTypes =
                new ArrayList<>(pdpStatusParameters.getSupportedPolicyTypes().size());
        for (final ToscaPolicyTypeIdentifierParameters policyTypeIdentParameters : pdpStatusParameters
                .getSupportedPolicyTypes()) {
            supportedPolicyTypes.add(new ToscaConceptIdentifier(policyTypeIdentParameters.getName(),
                    policyTypeIdentParameters.getVersion()));
        }
        return supportedPolicyTypes;
    }

    /**
     * Method to create PdpStatus message from the context, which is to be sent by apex-pdp to pap.
     *
     * @return PdpStatus the pdp status message
     */
    public PdpStatus createPdpStatusFromContext() {
        final var pdpStatusContext = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class);
        final var pdpStatus = new PdpStatus();
        pdpStatus.setName(pdpStatusContext.getName());
        pdpStatus.setPdpType(pdpStatusContext.getPdpType());
        pdpStatus.setState(pdpStatusContext.getState());
        pdpStatus.setHealthy(pdpStatusContext.getHealthy());
        pdpStatus.setDescription(pdpStatusContext.getDescription());
        pdpStatus.setPolicies(pdpStatusContext.getPolicies());
        pdpStatus.setPdpGroup(pdpStatusContext.getPdpGroup());
        pdpStatus.setPdpSubgroup(pdpStatusContext.getPdpSubgroup());

        ApexEngineHandler apexEngineHandler = null;
        try {
            apexEngineHandler = Registry.get(ApexStarterConstants.REG_APEX_ENGINE_HANDLER);
        } catch (IllegalArgumentException e) {
            LOGGER.warn(e.getMessage());
        }

        pdpStatus.setStatistics(getStatistics(pdpStatus, apexEngineHandler));


        return pdpStatus;
    }

    /**
     * Method to get the statistics.
     *
     * @return PdpStatistics the pdp status message
     */

    private PdpStatistics getStatistics(final PdpStatus pdpStatusContext, final ApexEngineHandler apexEngineHandler) {
        var pdpStatistics = new PdpStatistics();
        pdpStatistics.setPdpInstanceId(pdpStatusContext.getName());
        pdpStatistics.setTimeStamp(Instant.now());
        pdpStatistics.setPdpGroupName(pdpStatusContext.getPdpGroup());
        pdpStatistics.setPdpSubGroupName(pdpStatusContext.getPdpSubgroup());
        if (apexEngineHandler != null) {
            pdpStatistics.setEngineStats(getEngineWorkerStats(apexEngineHandler));
        }
        final var apexPolicyCounter = ApexPolicyStatisticsManager.getInstanceFromRegistry();
        if (apexPolicyCounter != null) {
            pdpStatistics.setPolicyDeploySuccessCount(apexPolicyCounter.getPolicyDeploySuccessCount());
            pdpStatistics.setPolicyDeployFailCount(apexPolicyCounter.getPolicyDeployFailCount());
            pdpStatistics.setPolicyDeployCount(apexPolicyCounter.getPolicyDeployCount());

            pdpStatistics.setPolicyUndeploySuccessCount(apexPolicyCounter.getPolicyUndeploySuccessCount());
            pdpStatistics.setPolicyUndeployFailCount(apexPolicyCounter.getPolicyUndeployFailCount());
            pdpStatistics.setPolicyUndeployCount(apexPolicyCounter.getPolicyUndeployCount());

            pdpStatistics.setPolicyExecutedCount(apexPolicyCounter.getPolicyExecutedCount());
            pdpStatistics.setPolicyExecutedSuccessCount(apexPolicyCounter.getPolicyExecutedSuccessCount());
            pdpStatistics.setPolicyExecutedFailCount(apexPolicyCounter.getPolicyExecutedFailCount());
        }
        return pdpStatistics;
    }

    private List<PdpEngineWorkerStatistics> getEngineWorkerStats(@NonNull final ApexEngineHandler apexEngineHandler) {
        List<PdpEngineWorkerStatistics> pdpEngineWorkerStats = new ArrayList<>();
        List<AxEngineModel> engineModels = apexEngineHandler.getEngineStats();
        if (engineModels != null) {
            engineModels.forEach(engineModel -> {
                var workerStatistics = new PdpEngineWorkerStatistics();
                workerStatistics.setEngineWorkerState(transferEngineState(engineModel.getState()));
                workerStatistics.setEngineId(engineModel.getId());
                workerStatistics.setEventCount(engineModel.getStats().getEventCount());
                workerStatistics.setAverageExecutionTime(engineModel.getStats().getAverageExecutionTime());
                workerStatistics.setEngineTimeStamp(engineModel.getStats().getTimeStamp());
                workerStatistics.setLastEnterTime(engineModel.getStats().getLastEnterTime());
                workerStatistics.setLastExecutionTime(engineModel.getStats().getLastExecutionTime());
                workerStatistics.setLastStart(engineModel.getStats().getLastStart());
                workerStatistics.setUpTime(engineModel.getStats().getUpTime());
                pdpEngineWorkerStats.add(workerStatistics);
            });
        }
        return pdpEngineWorkerStats;
    }

    private PdpEngineWorkerState transferEngineState(@NonNull final AxEngineState state) {
        switch (state) {
            case STOPPING:
                return PdpEngineWorkerState.STOPPING;
            case STOPPED:
                return PdpEngineWorkerState.STOPPED;
            case READY:
                return PdpEngineWorkerState.READY;
            case EXECUTING:
                return PdpEngineWorkerState.EXECUTING;
            default:
                return PdpEngineWorkerState.UNDEFINED;
        }
    }

    /**
     * Method to get a final pdp status when the apex started is shutting down.
     *
     * @return PdpStatus the pdp status message
     */
    public PdpStatus getTerminatedPdpStatus() {
        final var pdpStatusInContext = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class);
        pdpStatusInContext.setState(PdpState.TERMINATED);
        pdpStatusInContext.setDescription("Apex pdp shutting down.");
        return createPdpStatusFromContext();
    }

    /**
     * Method create PdpResponseDetails which will be sent as part of pdp status to PAP.
     *
     * @param requestId request id of the PdpUpdate message from pap
     * @param status response status to be sent back
     * @param responseMessage response message to be sent back
     *
     * @return PdpResponseDetails
     */
    public PdpResponseDetails createPdpResonseDetails(final String requestId, final PdpResponseStatus status,
            final String responseMessage) {
        final var pdpResponseDetails = new PdpResponseDetails();
        pdpResponseDetails.setResponseTo(requestId);
        pdpResponseDetails.setResponseStatus(status);
        pdpResponseDetails.setResponseMessage(responseMessage);
        return pdpResponseDetails;
    }

    /**
     * Method to retrieve list of ToscaPolicyIdentifier from the list of ToscaPolicy.
     *
     * @param policies list of ToscaPolicy
     *
     * @return policyTypeIdentifiers
     */
    public List<ToscaConceptIdentifier> getToscaPolicyIdentifiers(final List<ToscaPolicy> policies) {
        final List<ToscaConceptIdentifier> policyIdentifiers = new ArrayList<>(policies.size());
        for (final ToscaPolicy policy : policies) {
            if (null != policy.getName() && null != policy.getVersion()) {
                policyIdentifiers.add(new ToscaConceptIdentifier(policy.getName(), policy.getVersion()));
            }
        }
        return policyIdentifiers;
    }
}