aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/main/java/org/onap/policy/pap/main/notification/DeploymentStatus.java
blob: 20e5933902d0258f97e3300b90a156fb59b1bdf6 (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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/*-
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
 * Modifications Copyright (C) 2022 Bell Canada. 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.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.pap.main.notification;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.Getter;
import org.onap.policy.models.pap.concepts.PolicyNotification;
import org.onap.policy.models.pdp.concepts.PdpPolicyStatus;
import org.onap.policy.models.pdp.concepts.PdpPolicyStatus.State;
import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
import org.onap.policy.pap.main.notification.StatusAction.Action;
import org.onap.policy.pap.main.service.PolicyStatusService;

/**
 * Collection of Policy Deployment Status records. The sequence of method invocations
 * should be as follows:
 * <ol>
 * <li>{@link #loadByGroup(String)}</li>
 * <li>various other methods</li>
 * <li>repeat the previous steps as appropriate</li>
 * <li>{@link #flush(PolicyNotification)}</li>
 * </ol>
 */
public class DeploymentStatus {
    /**
     * Tracks the groups that have been loaded.
     */
    private final Set<String> pdpGroupLoaded = new HashSet<>();

    /**
     * Records, mapped by PDP/Policy pair.
     */
    @Getter(AccessLevel.PROTECTED)
    private final Map<StatusKey, StatusAction> recordMap = new HashMap<>();

    /**
     * Records the policy status so that notifications can be generated. When
     * {@link #loadByGroup(String)} is invoked, records are added to this. Other than
     * that, this is not updated until {@link #addNotifications(PolicyNotification)} is
     * invoked.
     */
    private DeploymentTracker tracker = new DeploymentTracker();

    private PolicyStatusService policyStatusService;


    /**
     * Constructs the object.
     *
     * @param policyStatusService the policyStatusService
     */
    public DeploymentStatus(PolicyStatusService policyStatusService) {
        this.policyStatusService = policyStatusService;
    }

    /**
     * Adds new policy status to a notification.
     *
     * @param notif notification to which to add policy status
     */
    protected void addNotifications(PolicyNotification notif) {
        var newTracker = new DeploymentTracker();
        recordMap.values().forEach(newTracker::add);

        tracker.addNotifications(notif, newTracker);

        tracker = newTracker;
    }

    /**
     * Loads policy deployment status associated with the given PDP group.
     *
     * @param pdpGroup group whose records are to be loaded
     */
    public void loadByGroup(String pdpGroup) {
        if (pdpGroupLoaded.contains(pdpGroup)) {
            return;
        }

        pdpGroupLoaded.add(pdpGroup);

        for (PdpPolicyStatus status : policyStatusService.getGroupPolicyStatus(pdpGroup)) {
            var status2 = new StatusAction(Action.UNCHANGED, status);
            recordMap.put(new StatusKey(status), status2);
            tracker.add(status2);
        }
    }

    /**
     * Flushes changes to the DB, adding policy status to the notification.
     *
     * @param notif notification to which to add policy status
     */
    public void flush(PolicyNotification notif) {
        // must add notifications BEFORE deleting undeployments
        addNotifications(notif);
        deleteUndeployments();
        flush();
    }

    /**
     * Flushes changes to the DB.
     */
    protected void flush() {
        // categorize the records
        List<PdpPolicyStatus> created = new ArrayList<>();
        List<PdpPolicyStatus> updated = new ArrayList<>();
        List<PdpPolicyStatus> deleted = new ArrayList<>();

        for (StatusAction status : recordMap.values()) {
            switch (status.getAction()) {
                case CREATED:
                    created.add(status.getStatus());
                    break;
                case UPDATED:
                    updated.add(status.getStatus());
                    break;
                case DELETED:
                    deleted.add(status.getStatus());
                    break;
                default:
                    break;
            }
        }

        policyStatusService.cudPolicyStatus(created, updated, deleted);

        /*
         * update the records to indicate everything is now unchanged (i.e., matches what
         * is in the DB)
         */

        Iterator<StatusAction> iter = recordMap.values().iterator();
        while (iter.hasNext()) {
            StatusAction status = iter.next();

            if (status.getAction() == Action.DELETED) {
                iter.remove();
            } else {
                status.setAction(Action.UNCHANGED);
            }
        }
    }

    /**
     * Deletes records for any policies that have been completely undeployed.
     */
    protected void deleteUndeployments() {
        // identify the incomplete policies

        // @formatter:off
        Set<ToscaConceptIdentifier> incomplete = recordMap.values().stream()
            .filter(status -> status.getAction() != Action.DELETED)
            .map(StatusAction::getStatus)
            .filter(status -> status.getState() == State.WAITING)
            .map(PdpPolicyStatus::getPolicy)
            .collect(Collectors.toSet());
        // @formatter:on

        // delete if UNDEPLOYED and not incomplete
        deleteDeployment((key, status) -> !status.getStatus().isDeploy() && !incomplete.contains(key.getPolicy()));
    }

    /**
     * Delete deployment records for a PDP.
     *
     * @param pdpId PDP whose records are to be deleted
     */
    public void deleteDeployment(String pdpId) {
        deleteDeployment((key, status) -> key.getPdpId().equals(pdpId));
    }

    /**
     * Delete deployment records for a policy.
     *
     * @param policy policy whose records are to be deleted
     * @param deploy {@code true} to delete deployment records, {@code false} to delete
     *        undeployment records
     */
    public void deleteDeployment(ToscaConceptIdentifier policy, boolean deploy) {
        deleteDeployment((key, status) -> status.getStatus().isDeploy() == deploy && key.getPolicy().equals(policy));
    }

    /**
     * Delete deployment records for a policy.
     *
     * @param filter filter to identify records to be deleted
     */
    private void deleteDeployment(BiPredicate<StatusKey, StatusAction> filter) {
        Iterator<Entry<StatusKey, StatusAction>> iter = recordMap.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<StatusKey, StatusAction> entry = iter.next();
            StatusKey key = entry.getKey();
            StatusAction value = entry.getValue();

            if (filter.test(key, value)) {
                if (value.getAction() == Action.CREATED) {
                    // it's a new record - just remove it
                    iter.remove();
                } else {
                    // it's an existing record - mark it for deletion
                    value.setAction(Action.DELETED);
                }
            }
        }
    }

    /**
     * Deploys/undeploys a policy to a PDP. Assumes that
     * {@link #deleteDeployment(ToscaConceptIdentifier, boolean)} has already been invoked
     * to delete any records having the wrong "deploy" value.
     *
     * @param pdpId PDP to which the policy is to be deployed
     * @param policy policy to be deployed
     * @param policyType policy's type
     * @param pdpGroup PdpGroup containing the PDP of interest
     * @param pdpType PDP type (i.e., PdpSubGroup) containing the PDP of interest
     * @param deploy {@code true} if the policy is being deployed, {@code false} if
     *        undeployed
     */
    public void deploy(String pdpId, ToscaConceptIdentifier policy, ToscaConceptIdentifier policyType, String pdpGroup,
                    String pdpType, boolean deploy) {

        recordMap.compute(new StatusKey(pdpId, policy), (key, status) -> {

            if (status == null) {
                // no record yet - create one

                // @formatter:off
                return new StatusAction(Action.CREATED, PdpPolicyStatus.builder()
                                    .pdpGroup(pdpGroup)
                                    .pdpId(pdpId)
                                    .pdpType(pdpType)
                                    .policy(policy)
                                    .policyType(policyType)
                                    .deploy(deploy)
                                    .state(State.WAITING)
                                    .build());
                // @formatter:on
            }

            PdpPolicyStatus status2 = status.getStatus();

            // record already exists - see if the deployment flag should be changed

            if (status2.isDeploy() != deploy) {
                // deployment flag has changed
                status.setChanged();
                status2.setDeploy(deploy);
                status2.setState(State.WAITING);


            } else if (status.getAction() == Action.DELETED) {
                // deployment flag is unchanged
                status.setAction(Action.UPDATED);
            }

            return status;
        });
    }

    /**
     * Indicates the deployment/undeployment of a set of policies to a PDP has completed.
     *
     * @param pdpId PDP of interest
     * @param expectedPolicies policies that we expected to be deployed to the PDP
     * @param actualPolicies policies that were actually deployed to the PDP
     */
    public void completeDeploy(String pdpId, Set<ToscaConceptIdentifier> expectedPolicies,
                    Set<ToscaConceptIdentifier> actualPolicies) {

        for (StatusAction status : recordMap.values()) {
            PdpPolicyStatus status2 = status.getStatus();

            if (!status.getStatus().getPdpId().equals(pdpId)
                            || expectedPolicies.contains(status2.getPolicy()) != status2.isDeploy()) {
                /*
                 * The policy is "expected" to be deployed, but the record is not marked
                 * for deployment (or vice versa), which means the expected policy is out
                 * of date with the DB, thus we'll ignore this policy for now.
                 */
                continue;
            }

            State state;
            if (actualPolicies.contains(status2.getPolicy())) {
                state = (status.getStatus().isDeploy() ? State.SUCCESS : State.FAILURE);
            } else {
                state = (status.getStatus().isDeploy() ? State.FAILURE : State.SUCCESS);
            }

            if (status2.getState() != state) {
                status.setChanged();
                status2.setState(state);
            }
        }
    }
}