aboutsummaryrefslogtreecommitdiffstats
path: root/cmso-service/src/main/java/org/onap/optf/cmso/optimizer/CmsoOptimizerHandler.java
blob: cb658bb6a9abcc98ae5edbcfcea8fa57c89de708 (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
/*******************************************************************************
 * Copyright © 2019 AT&T Intellectual Property.
 *
 * 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.optimizer;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.Response.Status;
import org.onap.observations.Observation;
import org.onap.optf.cmso.common.CMSStatusEnum;
import org.onap.optf.cmso.common.LogMessages;
import org.onap.optf.cmso.common.exceptions.CMSException;
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.ChangeManagementChangeWindowDAO;
import org.onap.optf.cmso.model.dao.ChangeManagementDetailDAO;
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.onap.optf.cmso.optimizer.model.OptimizerResponse;
import org.onap.optf.cmso.optimizer.model.OptimizerScheduleInfo;
import org.onap.optf.cmso.optimizer.model.ScheduledElement;
import org.onap.optf.cmso.optimizer.model.UnScheduledElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * The Class CmsoOptimizerHandler.
 */
@Component
public class CmsoOptimizerHandler {
    private static EELFLogger debug = EELFManager.getInstance().getDebugLogger();

    @Autowired
    Environment env;

    @Autowired
    ChangeManagementScheduleDAO cmScheduleDao;

    @Autowired
    ScheduleDAO scheduleDao;

    @Autowired
    ChangeManagementGroupDAO cmGroupDao;

    @Autowired
    ChangeManagementChangeWindowDAO cmChangeWindowDao;

    @Autowired
    ChangeManagementDetailDAO cmDetailsDao;

    /**
     * Handle optimizer response.
     *
     * @param response the response
     * @param schedule the schedule
     */
    public void handleOptimizerResponse(OptimizerResponse response, Schedule schedule) {
        try {
            // Note that transaction ID and schedule ID are currently the same value.

            String id = response.getRequestId();
            CMSStatusEnum status = CMSStatusEnum.PendingApproval.fromString(schedule.getStatus());
            debug.debug("Status at time of optimizer status is " + status.toString() + " for " + id);
            switch (status) {
                // PendingSchedule may be a valid status in the cases where SNIRO async call
                // returns before
                // We have committed the OptimizationInProgress status
                // The dispatch logic ensures that we only every dispatch once.
                case OptimizationInProgress:
                    processResponse(response, schedule);
                    scheduleDao.save(schedule);
                    break;
                default:
                    throw new CMSException(Status.PRECONDITION_FAILED, LogMessages.OPTIMIZER_CALLBACK_STATE_ERROR,
                                    CMSStatusEnum.OptimizationInProgress.toString(), schedule.getStatus().toString());
            }
        } catch (Exception e) {
            Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
        }
    }

    private void processResponse(OptimizerResponse response, Schedule schedule) {
        try {
            schedule.setOptimizerReturnDateTimeMillis(System.currentTimeMillis());
            schedule.setOptimizerStatus(response.getStatus().toString());
            schedule.setOptimizerMessage(response.getErrorMessage());
            switch (response.getStatus()) {
                case COMPLETED:
                    saveSchedules(response, schedule);
                    break;
                case FAILED:
                    schedule.setStatus(CMSStatusEnum.OptimizationFailed.toString());
                    break;
                case PENDING_OPTIMIZER:
                case PENDING_TICKETS:
                case PENDING_TOPOLOGY:
                    // Leave status as In progress
                    break;
                default:
                    break;
            }
            scheduleDao.save(schedule);
        } catch (CMSException e) {
            Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
            schedule.setStatus(CMSStatusEnum.OptimizationFailed.toString());
            schedule.setOptimizerStatus(e.getStatus().toString());
            schedule.setOptimizerMessage(e.getLocalizedMessage());
        } catch (Exception e) {
            Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
            schedule.setStatus(CMSStatusEnum.OptimizationFailed.toString());
            schedule.setOptimizerStatus("Exception");
            schedule.setOptimizerMessage(e.getLocalizedMessage());
        }
    }

    private void saveSchedules(OptimizerResponse response, Schedule schedule) throws CMSException {

        // TODO: Persist the list of schedules in the DB

        // For Dublin we choose the best schedule.
        // and only request Accept on that one.
        // FOr the future, the user will get to choose one of the persisted schedules
        List<OptimizerScheduleInfo> schedules = response.getSchedules();

        OptimizerScheduleInfo osi = chooseSchedule(schedules);
        if (osi == null) {
            schedule.setStatus(CMSStatusEnum.OptimizationFailed.toString());
            schedule.setOptimizerMessage("No schedules returned for COMPLETED status");
            return;
        }
        if (osi.getScheduledElements().size() == 0) {
            schedule.setStatus(CMSStatusEnum.OptimizationFailed.toString());
            schedule.setOptimizerMessage("No elements scheduled for COMPLETED status");
            return;
        }

        List<ChangeManagementGroup> groups = cmGroupDao.findBySchedulesId(schedule.getUuid());
        Map<String, ChangeManagementGroup> updatedGroups = new HashMap<>();

        for (ScheduledElement element : osi.getScheduledElements()) {
            updateGroup(element, groups, updatedGroups);
            String groupId = element.getGroupId();
            String vnfName = element.getElementId();
            ChangeManagementSchedule cms =
                            cmScheduleDao.findOneByScheduleUuidGroupIdAndVnfName(schedule.getUuid(), groupId, vnfName);
            cms.setStartTimeMillis(element.getStartTime().getTime());
            cms.setFinishTimeMillis(element.getEndTime().getTime());
            cms.setStatus(CMSStatusEnum.PendingApproval.toString());
            cmScheduleDao.save(cms);
        }
        if (osi.getUnScheduledElements() != null) {
            for (UnScheduledElement element : osi.getUnScheduledElements()) {
                String groupId = element.getGroupId();
                String vnfName = element.getElementId();
                ChangeManagementSchedule cms = cmScheduleDao.findOneByScheduleUuidGroupIdAndVnfName(schedule.getUuid(),
                                groupId, vnfName);
                cms.setStatus(CMSStatusEnum.NotScheduled.toString());
                cmScheduleDao.save(cms);

            }
        }

        // Save any changes to the groups
        for (ChangeManagementGroup cmg : updatedGroups.values()) {
            cmGroupDao.save(cmg);
        }
        schedule.setStatus(CMSStatusEnum.PendingApproval.toString());
    }

    private void updateGroup(ScheduledElement element, List<ChangeManagementGroup> groups,
                    Map<String, ChangeManagementGroup> updatedGroups) {

        // For Dublin the contents of CMG are not functional
        // since were are doing individual scheduling.
        // We log the not found exception, but do not
        // throw it at this time.
        try {
            ChangeManagementGroup cmg = updatedGroups.get(element.getGroupId());
            if (cmg == null) {
                for (ChangeManagementGroup group : groups) {
                    if (group.getGroupId().equals(element.getGroupId())) {
                        cmg = group;
                        break;
                    }
                }
            }
            if (cmg == null) {
                throw new CMSException(Status.INTERNAL_SERVER_ERROR, LogMessages.MISSING_VALID_GROUP_FOR_ELEMENT,
                                element.getElementId());
            }
            Long elementStartTime = element.getStartTime().getTime();
            Long elementFinishTime = element.getEndTime().getTime();
            if (cmg.getStartTimeMillis() == null || cmg.getStartTimeMillis() > elementStartTime) {
                cmg.setStartTimeMillis(elementStartTime);
                updatedGroups.put(cmg.getGroupId(), cmg);
            }
            if (cmg.getFinishTime() == null || cmg.getFinishTimeMillis() < elementFinishTime) {
                cmg.setFinishTimeMillis(elementFinishTime);
                updatedGroups.put(cmg.getGroupId(), cmg);
            }
            if (cmg.getLastInstanceStartTimeMillis() == null
                            || cmg.getLastInstanceStartTimeMillis() < elementStartTime) {
                cmg.setLastInstanceStartTimeMillis(elementStartTime);
                updatedGroups.put(cmg.getGroupId(), cmg);
            }
        } catch (Exception e) {
            Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
        }
    }

    private OptimizerScheduleInfo chooseSchedule(List<OptimizerScheduleInfo> schedules) {
        // The most scheduled elements is the priority
        //
        OptimizerScheduleInfo chosenOne = null;
        for (OptimizerScheduleInfo osi : schedules) {
            if (chosenOne == null || osi.getScheduledElements().size() > chosenOne.getScheduledElements().size()) {
                chosenOne = osi;
            } else {
                // Same number of scheduled elements.
                // What is the policy.
                if (betterSchedule(osi, chosenOne)) {
                    chosenOne = osi;
                }
            }
        }
        return chosenOne;
    }

    private boolean betterSchedule(OptimizerScheduleInfo osi, OptimizerScheduleInfo chosenOne) {
        // TODO Create a more sophisticated choosing process -
        return true;
    }
}