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

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.ws.rs.core.Response.Status;
import org.onap.optf.cmso.common.ApprovalStatusEnum;
import org.onap.optf.cmso.common.CmsoStatusEnum;
import org.onap.optf.cmso.common.LogMessages;
import org.onap.optf.cmso.common.exceptions.CmsoAlreadyExistsException;
import org.onap.optf.cmso.common.exceptions.CmsoException;
import org.onap.optf.cmso.common.exceptions.CmsoNotFoundException;
import org.onap.optf.cmso.model.ApprovalType;
import org.onap.optf.cmso.model.DomainData;
import org.onap.optf.cmso.model.Schedule;
import org.onap.optf.cmso.model.ScheduleApproval;
import org.onap.optf.cmso.model.dao.ApprovalTypeDao;
import org.onap.optf.cmso.model.dao.DomainDataDao;
import org.onap.optf.cmso.model.dao.ScheduleApprovalDao;
import org.onap.optf.cmso.model.dao.ScheduleDao;
import org.onap.optf.cmso.service.rs.models.ApprovalMessage;
import org.onap.optf.cmso.service.rs.models.v2.OptimizedScheduleMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class BaseSchedulerServiceImpl {
    private static EELFLogger log = EELFManager.getInstance().getLogger(BaseSchedulerServiceImpl.class);

    @Autowired
    protected ScheduleDao scheduleDao;

    @Autowired
    DomainDataDao domainDataDao;

    @Autowired
    ApprovalTypeDao approvalTypeDao;

    @Autowired
    ScheduleApprovalDao scheduleApprovalDao;

    protected Schedule validateAndAddScheduleRequest(OptimizedScheduleMessage scheduleMessage,
                    List<DomainData> domainData) throws CmsoException {
        messageValidations(scheduleMessage);
        Schedule sch = scheduleDao.findByDomainScheduleId(scheduleMessage.getDomain(), scheduleMessage.getScheduleId());

        if (sch != null) {
            throw new CmsoAlreadyExistsException(scheduleMessage.getDomain(), scheduleMessage.getScheduleId());
        }
        sch = new Schedule();
        sch.setUuid(UUID.randomUUID());
        sch.setUserId(scheduleMessage.getUserId());
        sch.setCreateDateTimeMillis(System.currentTimeMillis());
        sch.setDomain(scheduleMessage.getDomain());
        sch.setScheduleId(scheduleMessage.getScheduleId());
        sch.setOptimizerTransactionId(sch.getScheduleId()); // No reason these cannot be the same as
        // these
        // are 1<=>1 at this
        // point.
        sch.setScheduleName(scheduleMessage.getScheduleName());
        sch.setOptimizerAttemptsToSchedule(0);
        sch.setScheduleInfo(scheduleMessage.getSchedulingData().toString());
        sch.setStatus(CmsoStatusEnum.PendingSchedule.toString());
        scheduleDao.save(sch);
        for (DomainData dd : domainData) {
            dd.setUuid(UUID.randomUUID());
            sch.addDomainData(dd);
            domainDataDao.save(dd);
        }
        scheduleDao.save(sch);
        return sch;
    }

    private void messageValidations(OptimizedScheduleMessage scheduleMessage) throws CmsoException {
        if (scheduleMessage.getScheduleName() == null || scheduleMessage.getScheduleName().equals("")) {
            throw new CmsoException(Status.BAD_REQUEST, LogMessages.MISSING_REQUIRED_ATTRIBUTE, "schedulerName", "");
        }
        if (scheduleMessage.getUserId() == null || scheduleMessage.getUserId().equals("")) {
            throw new CmsoException(Status.BAD_REQUEST, LogMessages.MISSING_REQUIRED_ATTRIBUTE, "userId", "");
        }
    }

    protected void deleteScheduleRequest(String domain, String scheduleId) throws CmsoException {
        Schedule sch = scheduleDao.findByDomainScheduleId(domain, scheduleId);
        if (sch == null) {
            throw new CmsoNotFoundException(domain, scheduleId);
        }
        CmsoStatusEnum currentStatus = CmsoStatusEnum.Completed.fromString(sch.getStatus());
        sch.setDeleteDateTimeMillis(System.currentTimeMillis());
        switch (currentStatus) {
            case Scheduled:
                // TODO CLose all tickets....
                sch.setStatus(CmsoStatusEnum.Cancelled.toString());
                break;
            case NotificationsInitiated:
                throw new CmsoException(Status.NOT_ACCEPTABLE, LogMessages.CANNOT_CANCEL_IN_PROGRESS);
            default:
                sch.setStatus(CmsoStatusEnum.Deleted.toString());
        }
        scheduleDao.save(sch);
    }

    protected Schedule processApproval(Schedule sch, String domain, ApprovalMessage approvalMessage)
                    throws CmsoException {
        String scheduleId = sch.getScheduleId();
        ApprovalType approvalType =
                        approvalTypeDao.findByDomainAndType(domain, approvalMessage.getApprovalType().toString());
        if (approvalType == null) {
            throw new CmsoException(Status.BAD_REQUEST, LogMessages.INVALID_ATTRIBUTE, "approvalType",
                            approvalMessage.getApprovalType().toString());
        }

        if (!sch.getStatus().equals(CmsoStatusEnum.PendingApproval.toString())) {
            throw new CmsoException(Status.PRECONDITION_FAILED, LogMessages.NOT_PENDING_APPROVAL, domain, scheduleId,
                            sch.getStatus());
        }
        if (approvalMessage.getApprovalUserId() == null || approvalMessage.getApprovalUserId().equals("")) {
            throw new CmsoException(Status.BAD_REQUEST, LogMessages.MISSING_REQUIRED_ATTRIBUTE, "userId");
        }
        ScheduleApproval sa = null;
        // only 1 approval per user....
        if (sch.getScheduleApprovals() != null) {
            for (ScheduleApproval scheduleApproval : sch.getScheduleApprovals()) {
                if (scheduleApproval.getUserId().equals(approvalMessage.getApprovalUserId())
                                && scheduleApproval.getApprovalTypesUuid().equals(approvalType.getUuid())) {
                    sa = scheduleApproval;
                }
            }
        }
        if (sa == null) {
            sa = new ScheduleApproval();
            sa.setUuid(UUID.randomUUID());
            sa.setSchedule(sch);
            sa.setApprovalTypesUuid(approvalType.getUuid());
            sa.setUserId(approvalMessage.getApprovalUserId());
        }
        // Ignore what time is on the message
        sa.setApprovalDateTimeMillis(System.currentTimeMillis());
        sa.setStatus(approvalMessage.getApprovalStatus().toString());
        sa.setSchedule(sch);
        sch.addScheduleApproval(sa);
        scheduleDao.save(sch);
        if (sa.getStatus().equals(ApprovalStatusEnum.Rejected.toString())) {
            sch.setStatus(CmsoStatusEnum.Rejected.toString());
        } else {
            if (allApprovalsReceived(sch, sa)) {
                sch.setStatus(CmsoStatusEnum.Accepted.toString());
            }
        }
        scheduleDao.save(sch);
        return sch;
    }

    private boolean allApprovalsReceived(Schedule schedule, ScheduleApproval sa) {
        Map<UUID, Integer> requiredApprovalsByType = new HashMap<>(); // Approval
        // countdown
        Map<UUID, ApprovalType> approvalsByType = new HashMap<>(); // Just
        // for
        // logging

        List<ApprovalType> approvalTypes = approvalTypeDao.findByDomain(schedule.getDomain());
        for (ApprovalType at : approvalTypes) {
            UUID type = at.getUuid();
            Integer count = at.getApprovalCount();
            requiredApprovalsByType.put(type, count);
            approvalsByType.put(at.getUuid(), at);
        }

        // Account for approvals so far
        List<ScheduleApproval> existingApprovals = schedule.getScheduleApprovals();
        if (existingApprovals == null) {
            // This is necessary when doing automatic approvals because
            // the schedule will not return the approvals here
            existingApprovals = new ArrayList<ScheduleApproval>();
            existingApprovals.add(sa);
        }
        for (ScheduleApproval approval : existingApprovals) {
            if (approval.getStatus().equals(ApprovalStatusEnum.Accepted.toString())) {
                Integer remaining = requiredApprovalsByType.get(approval.getApprovalTypesUuid());
                if (remaining != null) {
                    remaining = remaining - 1;
                    requiredApprovalsByType.put(approval.getApprovalTypesUuid(), remaining);
                } else {
                    log.warn("Ignored Unidentified approval type {0} for domain {1}", approval.getApprovalTypesUuid(),
                                    schedule.getDomain());
                }
            }
        }
        for (UUID id : requiredApprovalsByType.keySet()) {
            Integer remaining = requiredApprovalsByType.get(id);
            if (remaining > 0) {
                return false;
            }
        }
        return true;
    }
}