Migrate pap startup & controllers to spring boot
[policy/pap.git] / main / src / main / java / org / onap / policy / pap / main / comm / PdpMessageGenerator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP PAP
4  * ================================================================================
5  * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2021 Nordix Foundation.
7  * Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pap.main.comm;
24
25 import java.util.LinkedList;
26 import java.util.List;
27 import org.onap.policy.common.parameters.ParameterService;
28 import org.onap.policy.common.utils.services.Registry;
29 import org.onap.policy.models.base.PfModelException;
30 import org.onap.policy.models.pap.concepts.PolicyNotification;
31 import org.onap.policy.models.pdp.concepts.PdpStateChange;
32 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
33 import org.onap.policy.models.pdp.concepts.PdpUpdate;
34 import org.onap.policy.models.pdp.enums.PdpState;
35 import org.onap.policy.models.provider.PolicyModelsProvider;
36 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
37 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
38 import org.onap.policy.pap.main.PapConstants;
39 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
40 import org.onap.policy.pap.main.notification.DeploymentStatus;
41 import org.onap.policy.pap.main.notification.PolicyNotifier;
42 import org.onap.policy.pap.main.parameters.PapParameterGroup;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.springframework.boot.context.event.ApplicationReadyEvent;
46 import org.springframework.context.event.EventListener;
47
48
49 /**
50  * PDP message generator used to generate PDP-UPDATE and PDP-STATE-CHANGE messages.
51  */
52 public class PdpMessageGenerator {
53     private static final Logger LOGGER = LoggerFactory.getLogger(PdpMessageGenerator.class);
54
55     private static final String PAP_GROUP_PARAMS_NAME = "PapGroup";
56
57     private boolean includeHeartBeat;
58     /**
59      * Lock used when updating PDPs.
60      */
61     protected Object updateLock;
62
63     /**
64      * Used to send UPDATE and STATE-CHANGE requests to the PDPs.
65      */
66     protected PdpModifyRequestMap requestMap;
67
68     /**
69      * Factory for PAP DAO.
70      */
71     protected PolicyModelsProviderFactoryWrapper modelProviderWrapper;
72
73     /**
74      * Heart beat interval, in milliseconds, to pass to PDPs, or {@code null}.
75      */
76     private Long heartBeatMs;
77
78     /**
79      * Constructs the object.
80      *
81      * @param includeHeartBeat if the heart beat interval is to be included in any
82      *        PDP-UPDATE messages
83      */
84     public PdpMessageGenerator(boolean includeHeartBeat) {
85         this.includeHeartBeat = includeHeartBeat;
86     }
87
88     /**
89      * Initialize the parameters.
90      */
91     @EventListener(ApplicationReadyEvent.class)
92     public void initialize() {
93         modelProviderWrapper = Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class);
94         updateLock = Registry.get(PapConstants.REG_PDP_MODIFY_LOCK, Object.class);
95         requestMap = Registry.get(PapConstants.REG_PDP_MODIFY_MAP, PdpModifyRequestMap.class);
96
97         if (includeHeartBeat) {
98             PapParameterGroup params = ParameterService.get(PAP_GROUP_PARAMS_NAME);
99             heartBeatMs = params.getPdpParameters().getHeartBeatMs();
100
101         } else {
102             heartBeatMs = null;
103         }
104     }
105
106     protected PdpUpdate createPdpUpdateMessage(final String pdpGroupName, final PdpSubGroup subGroup,
107                     final String pdpInstanceId,
108                     final List<ToscaPolicy> policiesToBeDeployed,
109                     final List<ToscaConceptIdentifier> policiesToBeUndeployed) {
110
111         final var update = new PdpUpdate();
112
113         update.setSource(PapConstants.PAP_NAME);
114         update.setName(pdpInstanceId);
115         update.setPdpGroup(pdpGroupName);
116         update.setPdpSubgroup(subGroup.getPdpType());
117         update.setPoliciesToBeDeployed(policiesToBeDeployed);
118         update.setPoliciesToBeUndeployed(policiesToBeUndeployed);
119         update.setPdpHeartbeatIntervalMs(heartBeatMs);
120
121         LOGGER.debug("Created PdpUpdate message - {}", update);
122         return update;
123     }
124
125     /**
126      * Method to return a list of policies.
127      *
128      * @param subGroup PdpSubGroup to retrieve policies from
129      * @param databaseProvider PolicyModelsProvider used to retrieve list of policies
130      * @returns a list of ToscaPolicy
131      **/
132     public List<ToscaPolicy> getToscaPolicies(final PdpSubGroup subGroup,
133             final PolicyModelsProvider databaseProvider)
134                     throws PfModelException {
135
136         final List<ToscaPolicy> policies = new LinkedList<>();
137         for (final ToscaConceptIdentifier policyIdentifier : subGroup.getPolicies()) {
138             policies.addAll(databaseProvider.getPolicyList(policyIdentifier.getName(), policyIdentifier.getVersion()));
139         }
140
141         LOGGER.debug("Created ToscaPolicy list - {}", policies);
142         return policies;
143     }
144
145     protected PdpStateChange createPdpStateChangeMessage(final String pdpGroupName, final PdpSubGroup subGroup,
146                     final String pdpInstanceId, final PdpState pdpState) {
147
148         final var stateChange = new PdpStateChange();
149         stateChange.setSource(PapConstants.PAP_NAME);
150         stateChange.setName(pdpInstanceId);
151         stateChange.setPdpGroup(pdpGroupName);
152         stateChange.setPdpSubgroup(subGroup.getPdpType());
153         stateChange.setState(pdpState == null ? PdpState.ACTIVE : pdpState);
154
155         LOGGER.debug("Created PdpStateChange message - {}", stateChange);
156         return stateChange;
157     }
158
159     /**
160      * If group state=ACTIVE AND updateMsg has policiesToDeploy, then make sure deployment status is updated
161      * If group state=PASSIVE, then delete any deployment information for a PDP.
162      *
163      * @param pdpGroupName the group name
164      * @param pdpType the pdp type
165      * @param pdpInstanceId the pdp instance
166      * @param pdpState the new state as per the PDP_STATE_CHANGE change message
167      * @param databaseProvider the database provider
168      * @param policies list of policies as per the PDP_UPDATE message
169      * @throws PfModelException the exception
170      */
171     protected void updateDeploymentStatus(final String pdpGroupName, final String pdpType, final String pdpInstanceId,
172         PdpState pdpState, final PolicyModelsProvider databaseProvider, List<ToscaPolicy> policies)
173         throws PfModelException {
174         var deploymentStatus = new DeploymentStatus(databaseProvider);
175         deploymentStatus.loadByGroup(pdpGroupName);
176         if (pdpState.equals(PdpState.PASSIVE)) {
177             deploymentStatus.deleteDeployment(pdpInstanceId);
178         } else if (pdpState.equals(PdpState.ACTIVE)) {
179             for (ToscaPolicy toscaPolicy : policies) {
180                 deploymentStatus.deploy(pdpInstanceId, toscaPolicy.getIdentifier(), toscaPolicy.getTypeIdentifier(),
181                     pdpGroupName, pdpType, true);
182             }
183         }
184         var notification = new PolicyNotification();
185         deploymentStatus.flush(notification);
186         PolicyNotifier notifier = Registry.get(PapConstants.REG_POLICY_NOTIFIER);
187         notifier.publish(notification);
188     }
189 }