aboutsummaryrefslogtreecommitdiffstats
path: root/cmso-service/src/main/java/org/onap/optf/cmso/service/rs/CmsoOptimizerCallbackImpl.java
blob: ffe00c5055ca9f325d686b6f89abb83532584545 (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
/*
 * Copyright © 2017-2019 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.service.rs;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.ISODateTimeFormat;
import org.onap.optf.cmso.common.CmsoStatusEnum;
import org.onap.optf.cmso.common.DomainsEnum;
import org.onap.optf.cmso.common.LogMessages;
import org.onap.optf.cmso.common.exceptions.CmsoException;
import org.onap.optf.cmso.common.exceptions.CmsoNotFoundException;
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.optimizer.bean.CmsoOptimizerResponse;
import org.onap.optf.cmso.optimizer.bean.CmsoSchedule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * The Class CmsoOptimizerCallbackImpl.
 */
@Controller
public class CmsoOptimizerCallbackImpl extends BaseSchedulerServiceImpl implements CmsoOptimizerCallback {
    private static EELFLogger log = EELFManager.getInstance().getLogger(CmsoOptimizerCallbackImpl.class);
    private static EELFLogger debug = EELFManager.getInstance().getDebugLogger();
    private static EELFLogger errors = EELFManager.getInstance().getErrorLogger();

    @Context
    UriInfo uri;

    @Context
    HttpServletRequest request;


    @Autowired
    ChangeManagementScheduleDao cmScheduleDao;

    @Autowired
    ChangeManagementGroupDao cmGroupDao;

    @Autowired
    ChangeManagementChangeWindowDao cmChangeWindowDao;

    @Autowired
    ChangeManagementDetailDao cmDetailsDaoO;

    /**
     * Sniro callback.
     *
     * @param apiVersion the api version
     * @param sniroResponse the sniro response
     * @return the response
     */
    @Override
    @Transactional
    public Response sniroCallback(String apiVersion, CmsoOptimizerResponse sniroResponse) {
        Response response = null;
        log.info(LogMessages.PROCESS_OPTIMIZER_CALLBACK, "Received", request.getRemoteAddr(), "");
        log.info(LogMessages.OPTIMIZER_REQUEST, "Callback received", sniroResponse.getTransactionId(),
                uri.getAbsolutePath().toString());
        try {
            // Note that transaction ID and schedule ID are currently the same value.

            String transactionId = sniroResponse.getTransactionId();

            // Synchronize this with transaction that scheduled the SNIRO optimization
            // to ensure status updates are properly ordered.
            // This is necessary only in the race condition where SNIRO callback comes
            // before the SNIRO response is processed and the scheduling transaction is
            // still in flight.
            // Note that this may happen in loopback mode, but is not likely to happen with
            // real SNIRO unless SNIRO changes to be synchronous and the callback comes before
            // the response.
            // If this lock times out, the schedule will remain in 'Optimization In
            // Progress' and never complete.
            Schedule schedule = scheduleDao.lockOneByTransactionId(transactionId);

            if (schedule == null) {
                throw new CmsoNotFoundException(DomainsEnum.ChangeManagement.toString(),
                        "(OptimizerTransactionID=" + transactionId + ")");

            }
            CmsoStatusEnum status = CmsoStatusEnum.PendingApproval.fromString(schedule.getStatus());
            debug.debug("Status at time of SNIRO callback is " + status.toString());
            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:
                    processSniroResponse(sniroResponse, schedule);
                    scheduleDao.save(schedule);
                    response = Response.ok().build();
                    break;
                default:
                    throw new CmsoException(Status.PRECONDITION_FAILED, LogMessages.OPTIMIZER_CALLBACK_STATE_ERROR,
                            CmsoStatusEnum.OptimizationInProgress.toString(), schedule.getStatus().toString());
            }
        } catch (CmsoException e) {
            errors.error(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
            response = Response.status(e.getStatus()).entity(e.getRequestError()).build();
        } catch (Exception e) {
            errors.error(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
            response = Response.serverError().entity(e.getMessage()).build();
        }
        return response;
    }

    private void processSniroResponse(CmsoOptimizerResponse sniroResponse, Schedule schedule) {
        try {
            schedule.setOptimizerReturnDateTimeMillis(System.currentTimeMillis());
            schedule.setOptimizerStatus(sniroResponse.getRequestState());
            schedule.setOptimizerMessage(sniroResponse.getDescription());
            String scheduleId = sniroResponse.getScheduleId();
            ObjectMapper om = new ObjectMapper();
            CmsoSchedule[] scheduleArray = sniroResponse.getSchedule();
            if (scheduleArray != null && scheduleArray.length > 0) {
                String scheduleString = om.writeValueAsString(scheduleArray);
                schedule.setSchedule(scheduleString);
                log.debug("scheduleId={0} schedule={1}", scheduleId, scheduleString);
                for (CmsoSchedule sniroSchedule : sniroResponse.getSchedule()) {
                    String groupId = sniroSchedule.getGroupId();
                    DateTime finishTime = convertDate(sniroSchedule.getFinishTime(), "finishTime");
                    DateTime startTime = convertDate(sniroSchedule.getStartTime(), "startTime");
                    ChangeManagementGroup group = cmGroupDao.findOneBySchedulesIdGroupId(schedule.getUuid(), groupId);
                    if (group == null) {
                        throw new CmsoException(Status.PRECONDITION_FAILED,
                                LogMessages.CHANGE_MANAGEMENT_GROUP_NOT_FOUND, schedule.getScheduleId(), groupId);
                    }
                    group.setStartTimeMillis(startTime.getMillis());
                    group.setFinishTimeMillis(finishTime.getMillis());
                    DateTime latestInstanceStartTime =
                                    convertDate(sniroSchedule.getLatestInstanceStartTime(), "latestInstanceStartTime");
                    group.setLastInstanceStartTimeMillis(latestInstanceStartTime.getMillis());
                    cmGroupDao.save(group);
                    long totalDuration =
                            (group.getAdditionalDurationInSecs() + group.getNormalDurationInSecs()) * 1000L;
                    Map<String, Map<String, Long>> startAndFinishTimeMap = new HashMap<String, Map<String, Long>>();
                    makeMap(startTime.getMillis(), latestInstanceStartTime.getMillis(), group.getConcurrencyLimit(),
                            totalDuration, sniroSchedule.getNode(), startAndFinishTimeMap);
                    for (String node : sniroSchedule.getNode()) {
                        processNode(schedule, group, node, startAndFinishTimeMap);
                    }
                }
                schedule.setStatus(CmsoStatusEnum.PendingApproval.toString());
            } else {
                debug.debug("scheduleId={0} schedule=null status={1} ", scheduleId, schedule.getOptimizerStatus());
                schedule.setStatus(CmsoStatusEnum.OptimizationFailed.toString());
            }
        } catch (CmsoException e) {
            errors.error(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
            schedule.setStatus(CmsoStatusEnum.OptimizationFailed.toString());
            schedule.setOptimizerStatus(e.getStatus().toString());
            schedule.setOptimizerMessage(e.getLocalizedMessage());
        } catch (Exception e) {
            errors.error(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
            schedule.setStatus(CmsoStatusEnum.OptimizationFailed.toString());
            schedule.setOptimizerStatus("Exception");
            schedule.setOptimizerMessage(e.getLocalizedMessage());
        }
    }

    /**
     * Make map.
     *
     * @param startTime the start time
     * @param latestInstanceStartTime the latest instance start time
     * @param concurrencyLimit the concurrency limit
     * @param totalDuration the total duration
     * @param nodeList the node list
     * @param startAndFinishTimeMap the start and finish time map
     * @throws CmsoException the CMS exception
     */
    public static void makeMap(Long startTime, Long latestInstanceStartTime, int concurrencyLimit, long totalDuration,
            List<String> nodeList, Map<String, Map<String, Long>> startAndFinishTimeMap) throws CmsoException {
        Long nextStartTime = null;
        Long nextFinishTime = null;
        for (int nodeNumber = 0; nodeNumber < nodeList.size(); nodeNumber++) {
            if (nodeNumber % concurrencyLimit == 0) {
                if (nodeNumber == 0) {
                    nextStartTime = startTime;
                }
                else {
                    nextStartTime = nextStartTime + totalDuration;
                }
                if (nextStartTime > latestInstanceStartTime) {
                    throw new CmsoException(Status.BAD_REQUEST, LogMessages.UNABLE_TO_ALLOCATE_VNF_TIMESLOTS,
                            startTime.toString(), latestInstanceStartTime.toString(), String.valueOf(totalDuration),
                            String.valueOf(concurrencyLimit), String.valueOf(nodeList.size()));
                }
                nextFinishTime = nextStartTime + totalDuration;
            }
            Map<String, Long> map = new HashMap<String, Long>();
            map.put("startTime", nextStartTime);
            map.put("finishTime", nextFinishTime);
            String node = nodeList.get(nodeNumber);
            startAndFinishTimeMap.put(node, map);
        }

    }

    private void processNode(Schedule schedule, ChangeManagementGroup group, String node,
            Map<String, Map<String, Long>> startAndFinishTimeMap) throws CmsoException {
        Map<String, Long> map = startAndFinishTimeMap.get(node);
        ChangeManagementSchedule detail = cmScheduleDao.findOneByGroupUuidAndVnfName(group.getUuid(), node);
        if (detail == null) {
            throw new CmsoException(Status.NOT_FOUND, LogMessages.UNABLE_TO_LOCATE_SCHEDULE_DETAIL,
                    schedule.getScheduleId(), group.getGroupId(), node);
        }
        detail.setStartTimeMillis(map.get("startTime"));
        detail.setFinishTimeMillis(map.get("finishTime"));
        detail.setVnfId("");
        detail.setStatus(CmsoStatusEnum.PendingApproval.toString());
        cmScheduleDao.save(detail);
    }

    /**
     * Convert date.
     *
     * @param utcDate the utc date
     * @param attrName the attr name
     * @return the date time
     * @throws CmsoException the CMS exception
     */
    public static DateTime convertDate(String utcDate, String attrName) throws CmsoException {
        try {
            DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZoneUTC().parseDateTime(utcDate);
            if (dateTime != null) {
                return dateTime;
            }
        } catch (Exception e) {
            debug.debug(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
        }
        throw new CmsoException(Status.BAD_REQUEST, LogMessages.INVALID_ATTRIBUTE, attrName, utcDate);
    }

    /**
     * Convert ISO date.
     *
     * @param utcDate the utc date
     * @param attrName the attr name
     * @return the date time
     * @throws CmsoException the CMS exception
     */
    public static DateTime convertIsoDate(String utcDate, String attrName) throws CmsoException {
        try {
            DateTime dateTime = ISODateTimeFormat.dateTimeParser().parseDateTime(utcDate);
            if (dateTime != null) {
                return dateTime;
            }
        } catch (Exception e) {
            debug.debug(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
        }
        throw new CmsoException(Status.BAD_REQUEST, LogMessages.INVALID_ATTRIBUTE, attrName, utcDate);
    }

}