aboutsummaryrefslogtreecommitdiffstats
path: root/cmso-service/src/main/java/org/onap/optf/cmso/ticketmgt/TmStatusClient.java
blob: 4ace56114d289ca78fd4f2c2e41f25aa6f1ca744 (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
/*
 * Copyright © 2017-2018 AT&T Intellectual Property. Modifications Copyright © 2018 IBM.
 *
 * 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.
 *
 *
 * Unless otherwise specified, all documentation contained herein is licensed under the Creative
 * Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * https://creativecommons.org/licenses/by/4.0/
 *
 * Unless required by applicable law or agreed to in writing, documentation 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.
 */

package org.onap.optf.cmso.ticketmgt;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.att.eelf.i18n.EELFResourceManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.transaction.Transactional;
import org.onap.optf.cmso.common.CmsoStatusEnum;
import org.onap.optf.cmso.common.LogMessages;
import org.onap.optf.cmso.common.exceptions.CmsoException;
import org.onap.optf.cmso.model.ChangeManagementGroup;
import org.onap.optf.cmso.model.ChangeManagementSchedule;
import org.onap.optf.cmso.model.Schedule;
import org.onap.optf.cmso.model.dao.ChangeManagementGroupDao;
import org.onap.optf.cmso.model.dao.ChangeManagementScheduleDao;
import org.onap.optf.cmso.model.dao.ScheduleDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Component
public class TmStatusClient {
    private static EELFLogger errors = EELFManager.getInstance().getErrorLogger();
    private static EELFLogger debug = EELFManager.getInstance().getDebugLogger();

    public enum GroupAuditStatus {
        InProgress, Completed, CompletedWithErrors
    }

    public enum ClosureCode {
        // Map to TM closure codes
        Successful("Successful As Scheduled"), Unsuccessful("Unsuccessful");

        private final String closureCode;

        private ClosureCode(String code) {
            closureCode = code;
        }

        @Override
        public String toString() {
            return closureCode;
        }
    }

    @Autowired
    Environment env;

    @Autowired
    ScheduleDao scheduleDao;

    @Autowired
    ChangeManagementScheduleDao cmScheduleDao;

    @Autowired
    ChangeManagementGroupDao cmGroupDao;

    @Autowired
    TmClient tmClient;

    /**
     * Check status.
     *
     * @param id the id
     */
    @Transactional
    public void checkStatus(String id) {
        debug.debug("Entered checkStatus id=" + id);
        try {
            // Multiple cmso instance support - re-get the record with a Schedule lock
            UUID uuid = UUID.fromString(id);
            Schedule sch = scheduleDao.lockOne(uuid);
            if (!sch.getStatus().equals(CmsoStatusEnum.NotificationsInitiated.toString())) {
                debug.debug(sch.getScheduleId() + " is no longer in " + CmsoStatusEnum.NotificationsInitiated.toString()
                                + " : it is " + sch.getStatus());
                // Attempt at avoiding race condition in a load balance env. ?
                return;
            }
            Map<GroupAuditStatus, List<ChangeManagementGroup>> groupStatus =
                            new HashMap<GroupAuditStatus, List<ChangeManagementGroup>>();
            List<ChangeManagementGroup> groups = cmGroupDao.findBySchedulesId(uuid);

            // Close tickets for completed VNFs
            for (ChangeManagementGroup group : groups) {
                processGroup(sch, group);
            }

            // Check overall status of schedule.
            //
            for (ChangeManagementGroup group : groups) {
                GroupAuditStatus status = auditGroupStatus(sch, group);
                List<ChangeManagementGroup> list = groupStatus.get(status);
                if (list == null) {
                    list = new ArrayList<ChangeManagementGroup>();
                    groupStatus.put(status, list);
                }
                list.add(group);
            }
            // In progress
            if (groupStatus.containsKey(GroupAuditStatus.InProgress)) {
                return;
            }
            //
            if (groupStatus.containsKey(GroupAuditStatus.CompletedWithErrors)) {
                sch.setStatus(CmsoStatusEnum.CompletedWithError.toString());
            }
            if (groupStatus.containsKey(GroupAuditStatus.Completed)) {
                sch.setStatus(CmsoStatusEnum.Completed.toString());
            }
            scheduleDao.save(sch);
        } catch (Exception e) {
            errors.error(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            String msg = EELFResourceManager.format(LogMessages.UNEXPECTED_EXCEPTION, e.getMessage());
            errors.warn(msg, e);
        }
    }

    private void processGroup(Schedule sch, ChangeManagementGroup group) throws CmsoException {
        debug.debug("{Processing status of " + sch.getScheduleId() + " group=" + group.getGroupId());
        // Get status of all VNFs within a ticket within the group (Tickets will not
        // span groups)
        Map<String, List<ChangeManagementSchedule>> failed = new HashMap<String, List<ChangeManagementSchedule>>();
        Map<String, List<ChangeManagementSchedule>> inProgress = new HashMap<String, List<ChangeManagementSchedule>>();
        Map<String, List<ChangeManagementSchedule>> completed = new HashMap<String, List<ChangeManagementSchedule>>();
        Map<String, List<ChangeManagementSchedule>> tmClosed = new HashMap<String, List<ChangeManagementSchedule>>();
        List<ChangeManagementSchedule> cmSchedules = cmScheduleDao.findByChangeManagementGroupId(group.getUuid());
        for (ChangeManagementSchedule cmSchedule : cmSchedules) {
            String status = cmSchedule.getStatus();
            String tmStatus = cmSchedule.getTmStatus();
            CmsoStatusEnum cmsStatus = CmsoStatusEnum.Completed.fromString(status);
            switch (cmsStatus) {
                case Scheduled:
                case Triggered:
                    addTo(inProgress, cmSchedule);
                    break;
                case Failed:
                case PastDue:
                case Error:
                case Cancelled:
                case SchedulingFailed:
                case Deleted:
                    addTo(failed, cmSchedule);
                    break;
                case Completed:
                    addTo(completed, cmSchedule);
                    break;
                case ApprovalRejected:
                case PendingApproval:
                case PendingSchedule:
                case ScheduledImmediate:
                default:
                    errors.applicationEvent(
                                    "Unexpected Change Management schedule event status {0} encountered "
                                    + "after notification : scheduleId={1} vnfName={2}",
                                    status, sch.getScheduleId(), cmSchedule.getVnfName());
                    break;
            }
            if (tmStatus != null && tmStatus.equals("Closed")) {
                addTo(tmClosed, cmSchedule);
            }
        }
        debug.debug("{Status of " + sch.getScheduleId() + " Group " + group.getGroupId() + "\ncompleted="
                        + completed.keySet().toString() + "\ninProgress=" + inProgress.keySet().toString() + "\nfailed="
                        + failed.keySet().toString() + "\ntmCLosed=" + tmClosed.keySet().toString());

        // Remove all tickets from completed where there are still 'Triggered' VNFs
        for (String changeId : inProgress.keySet()) {
            completed.remove(changeId);
        }
        // Remove all tickets from completed where the ticket is already closed.
        for (String changeId : tmClosed.keySet()) {
            completed.remove(changeId);
        }

        // Do not know what to do with failed
        for (String changeId : failed.keySet()) {
            completed.remove(changeId);
            closeTheTicket(sch, group, changeId, failed.get(changeId), ClosureCode.Unsuccessful,
                            "Change management request failed for one or more VNFs");
        }

        // Remaining completed tickets should be closed
        debug.debug("{Final status of " + sch.getScheduleId() + " Group " + group.getGroupId() + "\ncompleted="
                        + completed.keySet().toString() + "\ninProgress=" + inProgress.keySet().toString() + "\nfailed="
                        + failed.keySet().toString() + "\ntmCLosed=" + tmClosed.keySet().toString());
        for (String changeId : completed.keySet()) {
            closeTheTicket(sch, group, changeId, completed.get(changeId), ClosureCode.Successful,
                            ClosureCode.Successful.toString());
        }

    }

    private GroupAuditStatus auditGroupStatus(Schedule sch, ChangeManagementGroup group) {
        // Determine group status and synchronize VNF status with Ticket status.
        Map<String, List<ChangeManagementSchedule>> failed = new HashMap<String, List<ChangeManagementSchedule>>();
        Map<String, List<ChangeManagementSchedule>> inProgress = new HashMap<String, List<ChangeManagementSchedule>>();
        Map<String, List<ChangeManagementSchedule>> completed = new HashMap<String, List<ChangeManagementSchedule>>();
        Map<String, List<ChangeManagementSchedule>> tmClosed = new HashMap<String, List<ChangeManagementSchedule>>();
        Set<String> vnfNames = new HashSet<String>();
        Set<String> allNames = new HashSet<String>();
        Set<String> failedNames = new HashSet<String>();
        Set<String> completedNames = new HashSet<String>();
        List<ChangeManagementSchedule> cmSchedules = cmScheduleDao.findByChangeManagementGroupId(group.getUuid());
        for (ChangeManagementSchedule cmSchedule : cmSchedules) {
            String vnfName = cmSchedule.getVnfName();
            vnfNames.add(vnfName);
            allNames.add(vnfName);
            String status = cmSchedule.getStatus();
            String tmStatus = cmSchedule.getTmStatus();
            CmsoStatusEnum cmsStatus = CmsoStatusEnum.Completed.fromString(status);
            switch (cmsStatus) {
                case Scheduled:
                case Triggered:
                    addTo(inProgress, cmSchedule);
                    break;
                case Failed:
                case PastDue:
                case Error:
                case Cancelled:
                case SchedulingFailed:
                case Deleted:
                    failedNames.add(vnfName);
                    addTo(failed, cmSchedule);
                    break;
                case Completed:
                    completedNames.add(vnfName);
                    addTo(completed, cmSchedule);
                    break;
                case ApprovalRejected:
                case PendingApproval:
                case PendingSchedule:
                case ScheduledImmediate:
                default:
                    errors.applicationEvent(
                                    "Unexpected Change Management schedule event status {0} encountered"
                                    + " after notification : scheduleId={1} vnfName={2}",
                                    status, sch.getScheduleId(), cmSchedule.getVnfName());
                    break;
            }
            if (tmStatus != null && tmStatus.equals("Closed")) {
                addTo(tmClosed, cmSchedule);
            }
        }

        // We have at least 1 ticket with VNFs in progress. Leave schedule status as is.
        if (inProgress.size() > 0) {
            return GroupAuditStatus.InProgress;
        }

        // All VNFs are either failed or completed (or there is a bug.)

        allNames.removeAll(completedNames);
        if (allNames.size() == 0) {
            return GroupAuditStatus.Completed;
        }
        allNames.removeAll(failedNames);
        if (allNames.size() == 0) {
            return GroupAuditStatus.CompletedWithErrors;
        }
        return null;
    }

    private void addTo(Map<String, List<ChangeManagementSchedule>> map, ChangeManagementSchedule cmSchedule) {
        String changeId = cmSchedule.getTmChangeId();
        List<ChangeManagementSchedule> list = map.get(changeId);
        if (list == null) {
            list = new ArrayList<ChangeManagementSchedule>();
            map.put(changeId, list);
        }
        list.add(cmSchedule);

    }

    private void closeTheTicket(Schedule sch, ChangeManagementGroup group, String changeId,
                    List<ChangeManagementSchedule> list, ClosureCode closureCode, String closingComments)
                    throws CmsoException {
        debug.debug("Closing ticket " + changeId + ":" + closureCode);
        try {
            tmClient.closeTicket(sch, group, list, changeId, closureCode, closingComments);
            for (ChangeManagementSchedule cms : list) {
                cms.setTmStatus("Closed");
                cmScheduleDao.save(cms);
            }
        } catch (CmsoException e) {
            throw e;
        }

    }

}