Topic names in PAP should be configurable from application.yaml
[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-2022 Nordix Foundation.
7  * Modifications Copyright (C) 2021-2022 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 lombok.Getter;
28 import org.onap.policy.common.parameters.ParameterService;
29 import org.onap.policy.common.utils.services.Registry;
30 import org.onap.policy.models.base.PfModelException;
31 import org.onap.policy.models.pap.concepts.PolicyNotification;
32 import org.onap.policy.models.pdp.concepts.PdpStateChange;
33 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
34 import org.onap.policy.models.pdp.concepts.PdpUpdate;
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.onap.policy.pap.main.PapConstants;
39 import org.onap.policy.pap.main.notification.DeploymentStatus;
40 import org.onap.policy.pap.main.notification.PolicyNotifier;
41 import org.onap.policy.pap.main.parameters.PapParameterGroup;
42 import org.onap.policy.pap.main.service.PolicyStatusService;
43 import org.onap.policy.pap.main.service.ToscaServiceTemplateService;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.beans.factory.annotation.Value;
48 import org.springframework.boot.context.event.ApplicationReadyEvent;
49 import org.springframework.context.event.EventListener;
50
51
52 /**
53  * PDP message generator used to generate PDP-UPDATE and PDP-STATE-CHANGE messages.
54  */
55 public class PdpMessageGenerator {
56     private static final Logger LOGGER = LoggerFactory.getLogger(PdpMessageGenerator.class);
57
58     private final boolean includeHeartBeat;
59     /**
60      * Lock used when updating PDPs.
61      */
62     protected Object updateLock;
63
64     /**
65      * Used to send UPDATE and STATE-CHANGE requests to the PDPs.
66      */
67     protected PdpModifyRequestMap requestMap;
68
69     /**
70      * Heart beat interval, in milliseconds, to pass to PDPs, or {@code null}.
71      */
72     private Long heartBeatMs;
73
74     @Autowired
75     private ToscaServiceTemplateService toscaService;
76
77     @Autowired
78     private PolicyStatusService policyStatusService;
79
80     @Autowired
81     private PolicyNotifier policyNotifier;
82
83     @Getter
84     @Value("${pap.name}")
85     private String papGroupParamName = "PapGroup";
86
87     /**
88      * Constructs the object.
89      *
90      * @param includeHeartBeat if the heart beat interval is to be included in any
91      *        PDP-UPDATE messages
92      */
93     public PdpMessageGenerator(boolean includeHeartBeat) {
94         this.includeHeartBeat = includeHeartBeat;
95     }
96
97     /**
98      * Initialize the parameters.
99      */
100     @EventListener(ApplicationReadyEvent.class)
101     public void initialize() {
102         updateLock = Registry.get(PapConstants.REG_PDP_MODIFY_LOCK, Object.class);
103         requestMap = Registry.get(PapConstants.REG_PDP_MODIFY_MAP, PdpModifyRequestMap.class);
104
105         if (includeHeartBeat) {
106             PapParameterGroup params = ParameterService.get(papGroupParamName);
107             heartBeatMs = params.getPdpParameters().getHeartBeatMs();
108
109         } else {
110             heartBeatMs = null;
111         }
112     }
113
114     protected PdpUpdate createPdpUpdateMessage(final String pdpGroupName, final PdpSubGroup subGroup,
115                     final String pdpInstanceId,
116                     final List<ToscaPolicy> policiesToBeDeployed,
117                     final List<ToscaConceptIdentifier> policiesToBeUndeployed) {
118
119         final var update = new PdpUpdate();
120
121         update.setSource(PapConstants.PAP_NAME);
122         update.setName(pdpInstanceId);
123         update.setPdpGroup(pdpGroupName);
124         update.setPdpSubgroup(subGroup.getPdpType());
125         update.setPoliciesToBeDeployed(policiesToBeDeployed);
126         update.setPoliciesToBeUndeployed(policiesToBeUndeployed);
127         update.setPdpHeartbeatIntervalMs(heartBeatMs);
128
129         LOGGER.debug("Created PdpUpdate message - {}", update);
130         return update;
131     }
132
133     /**
134      * Method to return a list of policies.
135      *
136      * @param subGroup PdpSubGroup to retrieve policies from
137      * @return a list of ToscaPolicy
138      * @throws PfModelException the exception
139      **/
140     public List<ToscaPolicy> getToscaPolicies(final PdpSubGroup subGroup) throws PfModelException {
141
142         final List<ToscaPolicy> policies = new LinkedList<>();
143         for (final ToscaConceptIdentifier policyIdentifier : subGroup.getPolicies()) {
144             policies.addAll(toscaService.getPolicyList(policyIdentifier.getName(), policyIdentifier.getVersion()));
145         }
146
147         LOGGER.debug("Created ToscaPolicy list - {}", policies);
148         return policies;
149     }
150
151     protected PdpStateChange createPdpStateChangeMessage(final String pdpGroupName, final PdpSubGroup subGroup,
152                     final String pdpInstanceId, final PdpState pdpState) {
153
154         final var stateChange = new PdpStateChange();
155         stateChange.setSource(PapConstants.PAP_NAME);
156         stateChange.setName(pdpInstanceId);
157         stateChange.setPdpGroup(pdpGroupName);
158         stateChange.setPdpSubgroup(subGroup.getPdpType());
159         stateChange.setState(pdpState == null ? PdpState.ACTIVE : pdpState);
160
161         LOGGER.debug("Created PdpStateChange message - {}", stateChange);
162         return stateChange;
163     }
164
165     /**
166      * If group state=ACTIVE AND updateMsg has policiesToDeploy, then make sure deployment status is updated
167      * If group state=PASSIVE, then delete any deployment information for a PDP.
168      *
169      * @param pdpGroupName the group name
170      * @param pdpType the pdp type
171      * @param pdpInstanceId the pdp instance
172      * @param pdpState the new state as per the PDP_STATE_CHANGE change message
173      * @param policies list of policies as per the PDP_UPDATE message
174      */
175     protected void updateDeploymentStatus(final String pdpGroupName, final String pdpType, final String pdpInstanceId,
176         PdpState pdpState, List<ToscaPolicy> policies) {
177         var deploymentStatus = new DeploymentStatus(policyStatusService);
178         deploymentStatus.loadByGroup(pdpGroupName);
179         if (pdpState.equals(PdpState.PASSIVE)) {
180             deploymentStatus.deleteDeployment(pdpInstanceId);
181         } else if (pdpState.equals(PdpState.ACTIVE)) {
182             for (ToscaPolicy toscaPolicy : policies) {
183                 deploymentStatus.deploy(pdpInstanceId, toscaPolicy.getIdentifier(), toscaPolicy.getTypeIdentifier(),
184                     pdpGroupName, pdpType, true);
185             }
186         }
187         var notification = new PolicyNotification();
188         deploymentStatus.flush(notification);
189         policyNotifier.publish(notification);
190     }
191 }