Generate notifications when policies change
[policy/pap.git] / main / src / main / java / org / onap / policy / pap / main / rest / depundep / PdpGroupDeleteProvider.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP PAP
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pap.main.rest.depundep;
22
23 import java.util.Iterator;
24 import java.util.Set;
25 import java.util.function.Predicate;
26 import java.util.stream.Collectors;
27 import javax.ws.rs.core.Response.Status;
28 import org.onap.policy.models.base.PfModelException;
29 import org.onap.policy.models.pdp.concepts.Pdp;
30 import org.onap.policy.models.pdp.concepts.PdpGroup;
31 import org.onap.policy.models.pdp.enums.PdpState;
32 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
33 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
34 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * Provider for PAP component to delete PDP groups.
40  */
41 public class PdpGroupDeleteProvider extends ProviderBase {
42     private static final Logger logger = LoggerFactory.getLogger(PdpGroupDeleteProvider.class);
43
44
45     /**
46      * Constructs the object.
47      */
48     public PdpGroupDeleteProvider() {
49         super();
50     }
51
52     /**
53      * Deletes a PDP group.
54      *
55      * @param groupName name of the PDP group to be deleted
56      * @throws PfModelException if an error occurred
57      */
58     public void deleteGroup(String groupName) throws PfModelException {
59         process(groupName, this::deleteGroup);
60     }
61
62     /**
63      * Deletes a PDP group.
64      *
65      * @param data session data
66      * @param groupName name of the PDP group to be deleted
67      * @throws PfModelException if an error occurred
68      */
69     private void deleteGroup(SessionData data, String groupName) throws PfModelException {
70         try {
71             PdpGroup group = data.getGroup(groupName);
72             if (group == null) {
73                 throw new PfModelException(Status.NOT_FOUND, "group not found");
74             }
75
76             if (group.getPdpGroupState() == PdpState.ACTIVE) {
77                 throw new PfModelException(Status.BAD_REQUEST, "group is still " + PdpState.ACTIVE);
78             }
79
80             data.deleteGroupFromDb(group);
81
82         } catch (PfModelException | RuntimeException e) {
83             // no need to log the error object here, as it will be logged by the invoker
84             logger.warn("failed to delete group: {}", groupName);
85             throw e;
86         }
87     }
88
89     /**
90      * Undeploys a policy.
91      *
92      * @param policyIdent identifier of the policy to be undeployed
93      * @throws PfModelException if an error occurred
94      */
95     public void undeploy(ToscaPolicyIdentifierOptVersion policyIdent) throws PfModelException {
96         process(policyIdent, this::undeployPolicy);
97     }
98
99     /**
100      * Undeploys a policy from its groups.
101      *
102      * @param data session data
103      * @param ident identifier of the policy to be deleted
104      * @throws PfModelException if an error occurred
105      */
106     private void undeployPolicy(SessionData data, ToscaPolicyIdentifierOptVersion ident) throws PfModelException {
107         try {
108             processPolicy(data, ident);
109
110             if (data.isUnchanged()) {
111                 throw new PfModelException(Status.BAD_REQUEST, "policy does not appear in any PDP group: "
112                                 + ident.getName() + " " + ident.getVersion());
113             }
114
115         } catch (PfModelException | RuntimeException e) {
116             // no need to log the error object here, as it will be logged by the invoker
117             logger.warn("failed to undeploy policy: {}", ident);
118             throw e;
119         }
120     }
121
122     /**
123      * Returns a function that will remove the desired policy from a subgroup.
124      */
125     @Override
126     protected Updater makeUpdater(SessionData data, ToscaPolicy policy,
127                     ToscaPolicyIdentifierOptVersion desiredIdent) {
128
129         // construct a matcher based on whether or not the version was specified
130         Predicate<ToscaPolicyIdentifier> matcher;
131
132         if (desiredIdent.getVersion() != null) {
133             // version was specified - match the whole identifier
134             matcher = policy.getIdentifier()::equals;
135
136         } else {
137             // version was not specified - match the name only
138             String desnm = desiredIdent.getName();
139             matcher = ident -> ident.getName().equals(desnm);
140         }
141
142
143         // return a function that will remove the policy from the subgroup
144         return (group, subgroup) -> {
145
146             Set<String> pdps = subgroup.getPdpInstances().stream().map(Pdp::getInstanceId).collect(Collectors.toSet());
147
148             boolean result = false;
149
150             Iterator<ToscaPolicyIdentifier> iter = subgroup.getPolicies().iterator();
151             while (iter.hasNext()) {
152                 ToscaPolicyIdentifier ident = iter.next();
153
154                 if (matcher.test(ident)) {
155                     result = true;
156                     iter.remove();
157                     logger.info("remove policy {} {} from subgroup {} {} count={}", ident.getName(), ident.getVersion(),
158                                     group.getName(), subgroup.getPdpType(), subgroup.getPolicies().size());
159
160                     data.trackUndeploy(ident, pdps);
161                 }
162             }
163
164             return result;
165         };
166     }
167 }