aboutsummaryrefslogtreecommitdiffstats
path: root/cmso-service/src/main/java/org/onap/optf/cmso/dispatcher/DispatchJob.java
blob: ccbc43072908312c3e7a0466ed7a3edf0e8acace (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
/*
 * 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.dispatcher;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.att.eelf.i18n.EELFResourceManager;
import java.net.InetAddress;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.onap.optf.cmso.common.CmsoStatusEnum;
import org.onap.optf.cmso.common.LogMessages;
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.onap.optf.cmso.ticketmgt.TmClient;
import org.onap.optf.cmso.ticketmgt.bean.TmApprovalStatusEnum;
import org.onap.optf.cmso.ticketmgt.bean.TmChangeInfo;
import org.onap.optf.cmso.ticketmgt.bean.TmStatusEnum;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * This is the service used to dispatch a job COuld not get QuartzJobBean to.
 * be @Transactional
 *
 */
@Component
public class DispatchJob {
    private static EELFLogger log = EELFManager.getInstance().getLogger(DispatchJob.class);
    private static EELFLogger errors = EELFManager.getInstance().getErrorLogger();
    private static EELFLogger debug = EELFManager.getInstance().getDebugLogger();

    @Autowired
    CmsoClient vidClient;

    @Autowired
    ChangeManagementScheduleDao cmScheduleDao;

    @Autowired
    ChangeManagementGroupDao cmGroupDao;

    @Autowired
    ScheduleDao scheduleDao;

    @Autowired
    TmClient tmClient;

    @Autowired
    Environment env;

    /**
     * Execute.
     *
     * @param id the id
     * @throws JobExecutionException the job execution exception
     */
    public void execute(UUID id) throws JobExecutionException {
        debug.debug(LogMessages.CM_JOB, "Entered");
        try {
            // No other instance can read this cmso until we are done.
            ChangeManagementSchedule cmSchedule = cmScheduleDao.lockOne(id);
            cmSchedule.setDispatcherInstance(InetAddress.getLocalHost().getHostAddress());
            ChangeManagementGroup group = cmGroupDao.findById(cmSchedule.getChangeManagementGroupUuid()).orElse(null);
            if (group != null) {
                Schedule schedule = scheduleDao.findById(group.getSchedulesUuid()).orElse(null);
                if (schedule != null) {
                    schedule.setStatus(CmsoStatusEnum.NotificationsInitiated.toString());
                    if (safeToDispatch(cmSchedule, schedule)) {
                        vidClient.dispatch(cmSchedule, schedule);
                    }
                }
            }

        } catch (Exception e) {
            log.warn("Unexpected exception", e);
        }
        debug.debug(LogMessages.CM_JOB, "Exited");

    }

    private boolean safeToDispatch(ChangeManagementSchedule cmSchedule, Schedule schedule) {

        Boolean scheduleImmediateEnabled = env.getProperty("cmso.cm.dispatch.immediate.enabled", Boolean.class, false);

        // *******************************************************************
        // SHould we read with a lock to avoid race condition?
        // Not sure there is any real value to that at the moment.
        //

        // *******************************************************************
        // Validate that the state is accurate.
        // Another instance may have dispatched
        if (!cmSchedule.getStatus().equals(CmsoStatusEnum.Scheduled.toString())
                && !cmSchedule.getStatus().equals(CmsoStatusEnum.ScheduledImmediate.toString())) {
            log.info("Attempt to dispatch an event that is in the incorrect state scheduleId={0}, vnf={1}, status={2}",
                    schedule.getScheduleId(), cmSchedule.getVnfName(), cmSchedule.getStatus());
            return false;
        }

        // *******************************************************************
        //
        // Validate ticket is still active with tm
        //
        // TODO
        if (cmSchedule.getTmChangeId() != null && !cmSchedule.getTmChangeId().equals("")) {
            if (!isChangeApproved(schedule, cmSchedule, scheduleImmediateEnabled)) {
                return false;
            }
        }

        // *******************************************************************
        //
        // If this is schedule immediate. Dispatch it!
        //
        if (cmSchedule.getFinishTimeMillis() == null) {
            if (scheduleImmediateEnabled) {
                debug.info("Dispatching an immediate request" + cmSchedule.getVnfName());
                return true;
            } else {
                // THis should not happen. If schedule immediate is not enables, it will fail
                // ticket approval check.
                // ... If we see this, it is a bug...
                String message = "Attempt to schedule immediate when immmediate scheduling is disabled: "
                        + cmSchedule.getVnfName();
                log.info(message);
                cmSchedule.setStatus(CmsoStatusEnum.SchedulingFailed.toString());
                cmSchedule.setStatusMessage(message);
                updateScheduleStatus(cmSchedule, schedule);
                return false;
            }
        }

        // *******************************************************************
        //
        // Validate that event is not past due. Time sensitive. Do not dispatch
        // Do not account for lead time. This should be inconsequential, maybe????
        //
        long now = System.currentTimeMillis();
        Long startTime = cmSchedule.getStartTimeMillis();

        long startMillis = startTime;
        if (now > startMillis) {
            String message = EELFResourceManager.format(LogMessages.SCHEDULE_PAST_DUE, schedule.getScheduleId(),
                    cmSchedule.getVnfName(), new Date(now).toString(), new Date(startMillis).toString());
            log.info(message);

            cmSchedule.setStatus(CmsoStatusEnum.PastDue.toString());
            cmSchedule.setStatusMessage(message);
            updateScheduleStatus(cmSchedule, schedule);
            return false;
        }

        // *******************************************************************
        // (Sleep until actual dispatch time...)
        // leadTime allows for preparing call to VID to the start of workflow.
        Integer leadTime = env.getProperty("cmso.cm.dispatch.lead.time.ms", Integer.class, 1000);
        long sleep = (startMillis - leadTime) - System.currentTimeMillis();
        if (sleep > 0L) {
            try {
                Thread.sleep(sleep);
            } catch (Exception e) {
                debug.debug(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
            }
        }
        return true;
    }

    private boolean isChangeApproved(Schedule schedule, ChangeManagementSchedule cmSchedule,
            Boolean scheduleImmediateEnabled) {
        String message = "";
        // ChangeManagementGroup group =
        // cmGroupDAO.findById(cmSchedule.getChangeManagementGroupsId()).orElse(null);
        // Long startDate = group.getStartTimeMillis();
        Set<String> vnfNames = new HashSet<String>();
        vnfNames.add(cmSchedule.getVnfName());
        TmChangeInfo info = tmClient.getChangeTicket(cmSchedule.getTmChangeId());
        String otherStatus = env.getProperty("vtm.status", "");
        String otherApprovalStatus = env.getProperty("vtm.approvalStatus", "");
        String statusConfig = env.getProperty("vtm.approvalStatus",
                TmApprovalStatusEnum.Approved.toString() + "|" + TmStatusEnum.Scheduled.toString());
        String[] statusList = statusConfig.split(",");
        if (info != null) {
            String approvalStatus = info.getApprovalStatus();
            String status = info.getStatus();
            debug.debug("Retrieved changeid=" + info.getChangeId() + " approvlStatus=" + approvalStatus + " status="
                    + status);
            String actualStatus = approvalStatus + "|" + status;
            for (String okStatus : statusList) {
                if (actualStatus.equals(okStatus)) {
                    return true;
                }
            }
            // Look for proper state for immediate VNFs
            debug.debug("Retrieved changeid=" + info.getChangeId() + " otherApprovlStatus=" + otherApprovalStatus
                    + " status=" + otherStatus);
            if (cmSchedule.getStartTime() == null && scheduleImmediateEnabled) {
                debug.debug("Ignoring status on immediate schedule: " + cmSchedule.getTmChangeId());
                return true;
            }
            message = EELFResourceManager.format(LogMessages.CM_TICKET_NOT_APPROVED, schedule.getScheduleId(),
                    cmSchedule.getVnfName(), cmSchedule.getTmChangeId(), status, approvalStatus);
            log.warn(message);
        } else {
            message = EELFResourceManager.format(LogMessages.UNABLE_TO_LOCATE_CHANGE_RECORD, schedule.getScheduleId(),
                    cmSchedule.getVnfName(), cmSchedule.getTmChangeId());
            errors.error(message);
        }
        cmSchedule.setStatus(CmsoStatusEnum.SchedulingFailed.toString());
        cmSchedule.setStatusMessage(message);
        updateScheduleStatus(cmSchedule, schedule);
        return false;
    }

    /**
     * Update schedule status.
     *
     * @param cmSchedule the cm schedule
     * @param schedule the schedule
     */
    @Transactional
    public void updateScheduleStatus(ChangeManagementSchedule cmSchedule, Schedule schedule) {
        cmScheduleDao.save(cmSchedule);
        scheduleDao.save(schedule);

    }

}