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

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.onap.observations.Mdc;
import org.onap.optf.cmso.common.BasicAuthenticatorFilter;
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.PropertiesManagement;
import org.onap.optf.cmso.filters.CmsoClientFilters;
import org.onap.optf.cmso.model.Schedule;
import org.onap.optf.cmso.model.dao.ScheduleDao;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

/**
 * The Class OptimizerQuartzJob.
 */
@Component
@DisallowConcurrentExecution
public class OptimizerQuartzJob extends QuartzJobBean {
    private static EELFLogger log = EELFManager.getInstance().getLogger(OptimizerQuartzJob.class);
    private static EELFLogger debug = EELFManager.getInstance().getDebugLogger();
    private static EELFLogger errors = EELFManager.getInstance().getErrorLogger();

    @Autowired
    ScheduleDao scheduleDao;

    @Autowired
    PropertiesManagement pm;

    @Autowired
    Environment env;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        Mdc.quartzJobBegin(context);
        debug.debug(LogMessages.OPTIMIZER_QUARTZ_JOB, "Entered");

        // Turns out that this is not necessary. Quartz behaves in a way that makes
        // sense.
        // if (isStale(context))
        // return;

        try {
            // This job will look at the schedules waiting to go to Optimizer or waiting on response from
            // optimizer
            // (PendingSchedule, PendingOptimizer),
            // schedule the request and update the status to PendingSchedule
            // and update the state to OptimizationInProgress
            List<Schedule> schedules = scheduleDao.findByDomainStatus(DomainsEnum.ChangeManagement.toString(),
                            CmsoStatusEnum.PendingSchedule.toString());
            for (Schedule s : schedules) {
                scheduleOptimization(s);
            }
            List<Schedule> inProgressSchedules = scheduleDao.findByDomainStatus(DomainsEnum.ChangeManagement.toString(),
                            CmsoStatusEnum.OptimizationInProgress.toString());
            for (Schedule s : inProgressSchedules) {
                scheduleOptimization(s);
            }

        } catch (Exception e) {
            debug.debug(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
            errors.error(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
        }
        debug.debug(LogMessages.OPTIMIZER_QUARTZ_JOB, "Exited");

    }

    /**
     * Schedule optimization.
     *
     * @param sch the s
     */
    public void scheduleOptimization(Schedule sch) {
        UUID id = sch.getUuid();
        Map<String, String> mdcSave = Mdc.save();
        try {
            String url = env.getProperty("cmso.dispatch.url", "http://localhost:8089");
            String path = env.getProperty("cmso.dispatch.optimizer .path", "/cmso/dispatch/optimizer/");
            url = url + path + id;
            String user = env.getProperty("mechid.user", "");
            String pass = pm.getProperty("mechid.pass", "");
            Client client = ClientBuilder.newClient();
            client.register(new BasicAuthenticatorFilter(user, pass));
            client.register(new CmsoClientFilters());
            WebTarget target = client.target(url);
            Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON);
            Response response = null;
            response = invocationBuilder.get();
            switch (response.getStatus()) {
                case 200:
                    log.info("Returned from dispatch call");
                    break;
                case 400: // Bad request
                default: {

                    throw new SchedulerException(
                                    "Invalid return from dispach service: " + url + " : " + response.toString());
                }
            }
        } catch (Exception e) {
            debug.debug(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
            errors.error(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage());
        } finally {
            Mdc.restore(mdcSave);
        }

    }

    /**
     * According to the documentation I read, Quartz would queue a job without waiting for the
     * completion of the job with @DisallowConcurrentExecution to complete so that there would be a
     * backlog of triggers to process
     * This was designed to spin though these stale triggers. When this didn't work, I discovered that
     * the behavior is that Quartz will wait for the appropriate interval
     * after @DisallowConcurrentExecution jobs complete.
     * I tested by adding a sleep for an interval > the trigger interval
     * QUartz appears to do what makes sense. Leaving this here in case issues arise...
     *
     */
    @SuppressWarnings("unused")
    private boolean isStale(JobExecutionContext context) {
        // DO not process stale requests.
        long now = System.currentTimeMillis();
        long next = context.getNextFireTime().getTime();
        long sch = context.getScheduledFireTime().getTime();
        log.info("now=" + now);
        log.info("nxt=" + next);
        log.info("sch=" + sch);
        if (now > sch) {
            log.info("Skipping stale SNIRO job");
            // return true;
        }
        return false;
    }

}