001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *      http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.oozie.sla;
020
021import java.sql.Timestamp;
022import java.util.ArrayList;
023import java.util.Collections;
024import java.util.Date;
025import java.util.HashSet;
026import java.util.Iterator;
027import java.util.List;
028import java.util.Map;
029import java.util.Set;
030import java.util.concurrent.ConcurrentHashMap;
031
032import org.apache.hadoop.conf.Configuration;
033import org.apache.oozie.AppType;
034import org.apache.oozie.ErrorCode;
035import org.apache.oozie.XException;
036import org.apache.oozie.client.CoordinatorAction;
037import org.apache.oozie.client.OozieClient;
038import org.apache.oozie.client.WorkflowAction;
039import org.apache.oozie.client.WorkflowJob;
040import org.apache.oozie.client.event.JobEvent;
041import org.apache.oozie.client.event.SLAEvent.SLAStatus;
042import org.apache.oozie.client.rest.JsonBean;
043import org.apache.oozie.client.rest.RestConstants;
044import org.apache.oozie.command.CommandException;
045import org.apache.oozie.executor.jpa.BatchQueryExecutor;
046import org.apache.oozie.executor.jpa.BatchQueryExecutor.UpdateEntry;
047import org.apache.oozie.executor.jpa.JPAExecutorException;
048import org.apache.oozie.executor.jpa.SLARegistrationQueryExecutor;
049import org.apache.oozie.executor.jpa.SLARegistrationQueryExecutor.SLARegQuery;
050import org.apache.oozie.executor.jpa.SLASummaryQueryExecutor;
051import org.apache.oozie.executor.jpa.SLASummaryQueryExecutor.SLASummaryQuery;
052import org.apache.oozie.executor.jpa.sla.SLASummaryGetRecordsOnRestartJPAExecutor;
053import org.apache.oozie.service.ConfigurationService;
054import org.apache.oozie.service.EventHandlerService;
055import org.apache.oozie.service.InstrumentationService;
056import org.apache.oozie.service.JPAService;
057import org.apache.oozie.service.SchedulerService;
058import org.apache.oozie.service.ServiceException;
059import org.apache.oozie.service.Services;
060import org.apache.oozie.sla.service.SLAService;
061
062import com.google.common.annotations.VisibleForTesting;
063import org.apache.oozie.util.DateUtils;
064import org.apache.oozie.util.Instrumentation;
065import org.apache.oozie.util.LogUtils;
066import org.apache.oozie.util.Pair;
067import org.apache.oozie.util.XLog;
068
069/**
070 * Implementation class for SLACalculator that calculates SLA related to
071 * start/end/duration of jobs using a memory-based map
072 */
073public class SLACalculatorMemory implements SLACalculator {
074
075    private static XLog LOG = XLog.getLog(SLACalculatorMemory.class);
076    // TODO optimization priority based insertion/processing/bumping up-down
077    private Map<String, SLACalcStatus> slaMap;
078    protected Set<String> historySet;
079    private static int capacity;
080    private static JPAService jpaService;
081    protected EventHandlerService eventHandler;
082    private static int modifiedAfter;
083    private static long jobEventLatency;
084    private Instrumentation instrumentation;
085    public static final String INSTRUMENTATION_GROUP = "sla-calculator";
086    public static final String SLA_MAP = "sla-map";
087    private int maxRetryCount;
088
089    @Override
090    public void init(Configuration conf) throws ServiceException {
091        capacity = ConfigurationService.getInt(conf, SLAService.CONF_CAPACITY);
092        jobEventLatency = ConfigurationService.getInt(conf, SLAService.CONF_JOB_EVENT_LATENCY);
093        maxRetryCount = ConfigurationService.getInt(conf, SLAService.CONF_MAXIMUM_RETRY_COUNT);
094        slaMap = new ConcurrentHashMap<String, SLACalcStatus>();
095        historySet = Collections.synchronizedSet(new HashSet<String>());
096        jpaService = Services.get().get(JPAService.class);
097        eventHandler = Services.get().get(EventHandlerService.class);
098        instrumentation = Services.get().get(InstrumentationService.class).get();
099        // load events modified after
100        modifiedAfter = conf.getInt(SLAService.CONF_EVENTS_MODIFIED_AFTER, 7);
101        loadOnRestart();
102        Runnable purgeThread = new HistoryPurgeWorker();
103        // schedule runnable by default 1 hours
104        Services.get()
105                .get(SchedulerService.class)
106                .schedule(purgeThread, 3600, Services.get().getConf().getInt(SLAService.CONF_SLA_HISTORY_PURGE_INTERVAL, 3600),
107                        SchedulerService.Unit.SEC);
108    }
109
110    public class HistoryPurgeWorker extends Thread {
111
112        public HistoryPurgeWorker() {
113        }
114
115        @Override
116        public void run() {
117            if (Thread.currentThread().isInterrupted()) {
118                return;
119            }
120            Iterator<String> jobItr = historySet.iterator();
121            while (jobItr.hasNext()) {
122                String jobId = jobItr.next();
123                LOG.debug(" Running HistoryPurgeWorker for " + jobId);
124                try {
125                    boolean isDone = SLAXCommandFactory.getSLAJobHistoryXCommand(jobId).call();
126                    if (isDone) {
127                        LOG.debug("[{0}] job is finished and processed. Removing from history");
128                        jobItr.remove();
129                    }
130                }
131                catch (CommandException e) {
132                    if (e.getErrorCode().equals(ErrorCode.E0604) || e.getErrorCode().equals(ErrorCode.E0605)) {
133                        LOG.warn("Job is not found in db: " + jobId, e);
134                        jobItr.remove();
135                    }
136                    else {
137                        LOG.error("Failed to fetch the job: " + jobId, e);
138                    }
139                }
140            }
141        }
142    }
143
144    private void loadOnRestart() {
145        try {
146            List<SLASummaryBean> summaryBeans = jpaService
147                    .execute(new SLASummaryGetRecordsOnRestartJPAExecutor(modifiedAfter));
148            for (SLASummaryBean summaryBean : summaryBeans) {
149                String jobId = summaryBean.getId();
150                putAndIncrement(jobId, new SLACalcStatus(summaryBean));
151            }
152            LOG.info("Loaded {0} SLASummary object after restart", slaMap.size());
153        }
154        catch (Exception e) {
155            LOG.warn("Failed to retrieve SLASummary records on restart", e);
156        }
157    }
158
159    @Override
160    public int size() {
161        return slaMap.size();
162    }
163
164    @VisibleForTesting
165    public Set<String> getHistorySet(){
166        return historySet;
167    }
168
169    @Override
170    public SLACalcStatus get(String jobId) throws JPAExecutorException {
171        SLACalcStatus memObj;
172        memObj = slaMap.get(jobId);
173        if (memObj == null && historySet.contains(jobId)) {
174            memObj = new SLACalcStatus(SLASummaryQueryExecutor.getInstance()
175                    .get(SLASummaryQuery.GET_SLA_SUMMARY, jobId), SLARegistrationQueryExecutor.getInstance().get(
176                    SLARegQuery.GET_SLA_REG_ON_RESTART, jobId));
177        }
178        return memObj;
179    }
180
181    /**
182     * Get SLACalcStatus from map if SLARegistration is not null, else create a new SLACalcStatus
183     * This function deosn't update  slaMap
184     * @param jobId
185     * @return SLACalcStatus returns SLACalcStatus from map if SLARegistration is not null,
186     * else create a new SLACalcStatus
187     * @throws JPAExecutorException
188     */
189    private SLACalcStatus getOrCreateSLACalcStatus(String jobId) throws JPAExecutorException {
190        SLACalcStatus memObj;
191        memObj = slaMap.get(jobId);
192        // if the request came from immediately after restart don't use map SLACalcStatus.
193        if (memObj == null || memObj.getSLARegistrationBean() == null) {
194            SLARegistrationBean registrationBean = SLARegistrationQueryExecutor.getInstance()
195                    .get(SLARegQuery.GET_SLA_REG_ON_RESTART, jobId);
196            SLASummaryBean summaryBean = memObj == null
197                    ? SLASummaryQueryExecutor.getInstance().get(SLASummaryQuery.GET_SLA_SUMMARY, jobId)
198                    : memObj.getSLASummaryBean();
199            return new SLACalcStatus(summaryBean, registrationBean);
200        }
201        return memObj;
202    }
203
204    @Override
205    public Iterator<String> iterator() {
206        return slaMap.keySet().iterator();
207    }
208
209    @Override
210    public boolean isEmpty() {
211        return slaMap.isEmpty();
212    }
213
214    @Override
215    public void clear() {
216        final int originalSize = slaMap.size();
217        slaMap.clear();
218        historySet.clear();
219        instrumentation.decr(INSTRUMENTATION_GROUP, SLA_MAP, originalSize);
220    }
221
222    /**
223     * Invoked via periodic run, update the SLA for registered jobs.
224     * <p>
225     * Track the number of times the {@link SLACalcStatus} entry has not been processed successfully, and when a preconfigured
226     * {code oozie.sla.service.SLAService.maximum.retry.count} is reached, remove any {@link SLACalculatorMemory#slaMap} entries
227     * that are causing {@code JPAExecutorException}s of certain {@link ErrorCode}s.
228     * @param jobId the workflow or coordinator job or action ID the SLA is tracked against
229     */
230    void updateJobSla(String jobId) throws Exception {
231        SLACalcStatus slaCalc = slaMap.get(jobId);
232
233        if (slaCalc == null) {
234            // job might be processed and removed from map by addJobStatus
235            return;
236        }
237        boolean firstCheckAfterRetstart = checkAndUpdateSLACalcAfterRestart(slaCalc);
238        // get eventProcessed on DB for validation in HA
239        SLASummaryBean summaryBean = null;
240        try {
241            summaryBean = SLASummaryQueryExecutor.getInstance()
242                    .get(SLASummaryQuery.GET_SLA_SUMMARY_EVENTPROCESSED_LAST_MODIFIED, jobId);
243            resetRetryCount(jobId);
244        }
245        catch (final JPAExecutorException e) {
246            if (e.getErrorCode().equals(ErrorCode.E0603)
247                    || e.getErrorCode().equals(ErrorCode.E0604)
248                    || e.getErrorCode().equals(ErrorCode.E0605)) {
249                LOG.debug("job [{0}] is not in DB, removing from Memory", jobId);
250                incrementRetryCountAndRemove(jobId);
251                return;
252            }
253            throw e;
254        }
255        byte eventProc = summaryBean.getEventProcessed();
256        slaCalc.setEventProcessed(eventProc);
257        if (eventProc >= 7) {
258            if (eventProc == 7) {
259                historySet.add(jobId);
260            }
261            removeAndDecrement(jobId);
262            LOG.trace("Removed Job [{0}] from map as SLA processed", jobId);
263        }
264        else {
265            if (!slaCalc.getLastModifiedTime().equals(summaryBean.getLastModifiedTime())) {
266                // Update last modified time.
267                slaCalc.setLastModifiedTime(summaryBean.getLastModifiedTime());
268                reloadExpectedTimeAndConfig(slaCalc);
269                LOG.debug("Last modified time has changed for job " + jobId + " reloading config from DB");
270            }
271            if (firstCheckAfterRetstart || isChanged(slaCalc)) {
272                LOG.debug("{0} job has SLA event change. EventProc = {1}, status = {2}", slaCalc.getId(),
273                        slaCalc.getEventProcessed(), slaCalc.getJobStatus());
274                try {
275                    SLAXCommandFactory.getSLAEventXCommand(slaCalc).call();
276                    checkEventProc(slaCalc);
277                }
278                catch (XException e) {
279                    if (e.getErrorCode().equals(ErrorCode.E0604) || e.getErrorCode().equals(ErrorCode.E0605)) {
280                        LOG.debug("job [{0}] is is not in DB, removing from Memory", slaCalc.getId());
281                        removeAndDecrement(jobId);
282                    }
283                    else {
284                        if (firstCheckAfterRetstart) {
285                            slaCalc.setSLARegistrationBean(null);
286                        }
287                    }
288                }
289            }
290        }
291    }
292
293    private boolean isChanged(SLACalcStatus slaCalc) {
294        SLARegistrationBean reg = slaCalc.getSLARegistrationBean();
295        byte eventProc = slaCalc.getEventProcessed();
296
297        if ((eventProc & 1) == 0) { // first bit (start-processed) unset
298            if (reg.getExpectedStart() != null) {
299                if (reg.getExpectedStart().getTime() + jobEventLatency < System.currentTimeMillis()) {
300                    return true;
301                }
302            }
303            else {
304                return true;
305            }
306        }
307        if (eventProc != 8 && ((eventProc >> 1) & 1) == 0) {
308            if (reg.getExpectedDuration() == -1) {
309                return true;
310            }
311            else if (slaCalc.getActualStart() != null) {
312                if ((reg.getExpectedDuration() + jobEventLatency) < (System.currentTimeMillis() - slaCalc
313                        .getActualStart().getTime())) {
314                    return true;
315                }
316            }
317        }
318        if (eventProc < 4) {
319            if (reg.getExpectedEnd().getTime() + jobEventLatency < System.currentTimeMillis()) {
320                return true;
321            }
322        }
323        return false;
324    }
325
326    @SuppressWarnings("rawtypes")
327    private void updateDBSlaConfig(SLACalcStatus slaCalc, List<UpdateEntry> updateList) throws JPAExecutorException {
328        updateList.add(new UpdateEntry<SLARegQuery>(SLARegQuery.UPDATE_SLA_CONFIG, slaCalc.getSLARegistrationBean()));
329        slaCalc.setLastModifiedTime(new Date());
330        updateList.add(new UpdateEntry<SLASummaryQuery>(SLASummaryQuery.UPDATE_SLA_SUMMARY_LAST_MODIFIED_TIME,
331                new SLASummaryBean(slaCalc)));
332    }
333
334    @SuppressWarnings("rawtypes")
335    private void updateDBSlaExpectedValues(SLACalcStatus slaCalc, List<UpdateEntry> updateList)
336            throws JPAExecutorException {
337        slaCalc.setLastModifiedTime(new Date());
338        updateList.add(new UpdateEntry<SLARegQuery>(SLARegQuery.UPDATE_SLA_EXPECTED_VALUE, slaCalc
339                .getSLARegistrationBean()));
340        updateList.add(new UpdateEntry<SLASummaryQuery>(SLASummaryQuery.UPDATE_SLA_SUMMARY_FOR_EXPECTED_TIMES,
341                new SLASummaryBean(slaCalc)));
342    }
343
344    @SuppressWarnings("rawtypes")
345    private void executeBatchQuery(List<UpdateEntry> updateList) throws JPAExecutorException {
346        BatchQueryExecutor.getInstance().executeBatchInsertUpdateDelete(null, updateList, null);
347    }
348
349    /**
350     * Periodically run by the SLAService worker threads to update SLA status by
351     * iterating through all the jobs in the map
352     */
353    @Override
354    public void updateAllSlaStatus() {
355        LOG.info("Running periodic SLA check");
356        Iterator<String> iterator = slaMap.keySet().iterator();
357        while (iterator.hasNext()) {
358            String jobId = iterator.next();
359            try {
360                LOG.trace("Processing SLA for jobid={0}", jobId);
361                updateJobSla(jobId);
362            }
363            catch (Exception e) {
364                setLogPrefix(jobId);
365                LOG.error("Exception in SLA processing for job [{0}]", jobId, e);
366                LogUtils.clearLogPrefix();
367            }
368        }
369    }
370
371    /**
372     * Register a new job into the map for SLA tracking
373     * @return true if successful
374     */
375    @Override
376    public boolean addRegistration(String jobId, SLARegistrationBean reg) throws JPAExecutorException {
377        try {
378            if (slaMap.size() < capacity) {
379                SLACalcStatus slaCalc = new SLACalcStatus(reg);
380                slaCalc.setSLAStatus(SLAStatus.NOT_STARTED);
381                slaCalc.setJobStatus(getJobStatus(reg.getAppType()));
382                List<JsonBean> insertList = new ArrayList<JsonBean>();
383                final SLASummaryBean summaryBean = new SLASummaryBean(slaCalc);
384                final Timestamp currentTime = DateUtils.convertDateToTimestamp(new Date());
385                reg.setCreatedTimestamp(currentTime);
386                summaryBean.setCreatedTimestamp(currentTime);
387                insertList.add(reg);
388                insertList.add(summaryBean);
389                BatchQueryExecutor.getInstance().executeBatchInsertUpdateDelete(insertList, null, null);
390                putAndIncrement(jobId, slaCalc);
391                LOG.trace("SLA Registration Event - Job:" + jobId);
392                return true;
393            }
394            else {
395                setLogPrefix(reg.getId());
396                LOG.error(
397                        "SLACalculator memory capacity reached. Cannot add or update new SLA Registration entry for job [{0}]",
398                        reg.getId());
399                LogUtils.clearLogPrefix();
400            }
401        }
402        catch (JPAExecutorException jpa) {
403            throw jpa;
404        }
405        return false;
406    }
407
408    private String getJobStatus(AppType appType) {
409        String status = null;
410        switch (appType) {
411            case COORDINATOR_ACTION:
412                status = CoordinatorAction.Status.WAITING.name();
413                break;
414            case WORKFLOW_ACTION:
415                status = WorkflowAction.Status.PREP.name();
416                break;
417            case WORKFLOW_JOB:
418                status = WorkflowJob.Status.PREP.name();
419                break;
420            default:
421                break;
422        }
423        return status;
424    }
425
426    /**
427     * Update job into the map for SLA tracking
428     */
429    @Override
430    public boolean updateRegistration(String jobId, SLARegistrationBean reg) throws JPAExecutorException {
431        try {
432            if (slaMap.size() < capacity) {
433                SLACalcStatus slaCalc = new SLACalcStatus(reg);
434                slaCalc.setSLAStatus(SLAStatus.NOT_STARTED);
435                slaCalc.setJobStatus(getJobStatus(reg.getAppType()));
436
437                @SuppressWarnings("rawtypes")
438                List<UpdateEntry> updateList = new ArrayList<UpdateEntry>();
439                updateList.add(new UpdateEntry<SLARegQuery>(SLARegQuery.UPDATE_SLA_REG_ALL, reg));
440                updateList.add(new UpdateEntry<SLASummaryQuery>(SLASummaryQuery.UPDATE_SLA_SUMMARY_ALL,
441                        new SLASummaryBean(slaCalc)));
442                BatchQueryExecutor.getInstance().executeBatchInsertUpdateDelete(null, updateList, null);
443                putAndIncrement(jobId, slaCalc);
444                LOG.trace("SLA Registration Event - Job:" + jobId);
445                return true;
446            }
447            else {
448                setLogPrefix(reg.getId());
449                LOG.error(
450                        "SLACalculator memory capacity reached. Cannot add or update new SLA Registration entry for job [{0}]",
451                        reg.getId());
452                LogUtils.clearLogPrefix();
453            }
454        }
455        catch (JPAExecutorException jpa) {
456            throw jpa;
457        }
458        return false;
459    }
460
461    /**
462     * Remove job from being tracked in map
463     */
464    @Override
465    public void removeRegistration(String jobId) {
466        if (!removeAndDecrement(jobId)) {
467            historySet.remove(jobId);
468        }
469    }
470
471    /**
472     * Triggered after receiving Job status change event, update SLA status
473     * accordingly
474     */
475    @Override
476    public boolean addJobStatus(String jobId, String jobStatus, JobEvent.EventStatus jobEventStatus, Date startTime,
477            Date endTime) throws JPAExecutorException, ServiceException {
478        LOG.debug(
479                "Received addJobStatus request for job  [{0}] jobStatus = [{1}], jobEventStatus = [{2}], startTime = [{3}], "
480                        + "endTime = [{4}] ", jobId, jobStatus, jobEventStatus, startTime, endTime);
481        SLACalcStatus slaCalc = slaMap.get(jobId);
482        boolean firstCheckAfterRetstart = checkAndUpdateSLACalcAfterRestart(slaCalc);
483        if (slaCalc == null) {
484            SLARegistrationBean slaRegBean = SLARegistrationQueryExecutor.getInstance().get(
485                    SLARegQuery.GET_SLA_REG_ALL, jobId);
486            if (slaRegBean != null) { // filter out jobs picked by SLA job event listener
487                                      // but not actually configured for SLA
488                SLASummaryBean slaSummaryBean = SLASummaryQueryExecutor.getInstance().get(
489                        SLASummaryQuery.GET_SLA_SUMMARY, jobId);
490                slaCalc = new SLACalcStatus(slaSummaryBean, slaRegBean);
491                putAndIncrement(jobId, slaCalc);
492            }
493        }
494        else {
495            SLASummaryBean summaryBean = ((SLASummaryQueryExecutor) SLASummaryQueryExecutor.getInstance()).get(
496                    SLASummaryQuery.GET_SLA_SUMMARY_EVENTPROCESSED_LAST_MODIFIED, jobId);
497            byte eventProc = summaryBean.getEventProcessed();
498            if (!slaCalc.getLastModifiedTime().equals(summaryBean.getLastModifiedTime())) {
499                // Update last modified time.
500                slaCalc.setLastModifiedTime(summaryBean.getLastModifiedTime());
501                reloadExpectedTimeAndConfig(slaCalc);
502                LOG.debug("Last modified time has changed for job " + jobId + " reloading config from DB");
503
504            }
505            slaCalc.setEventProcessed(eventProc);
506        }
507        if (slaCalc != null) {
508            try {
509                SLAXCommandFactory.getSLAEventXCommand(slaCalc,
510                        ConfigurationService.getLong(SLAService.CONF_SLA_CALC_LOCK_TIMEOUT, 20 * 1000)).call();
511                checkEventProc(slaCalc);
512            }
513            catch (XException e) {
514                if (firstCheckAfterRetstart) {
515                    slaCalc.setSLARegistrationBean(null);
516                }
517                LOG.error(e);
518                throw new ServiceException(e);
519            }
520            return true;
521        }
522        else {
523            return false;
524        }
525    }
526
527    private void checkEventProc(SLACalcStatus slaCalc){
528        byte eventProc = slaCalc.getEventProcessed();
529        if (slaCalc.getEventProcessed() >= 8) {
530            removeAndDecrement(slaCalc.getId());
531            LOG.debug("Removed Job [{0}] from map after Event-processed=8", slaCalc.getId());
532        }
533        if (eventProc == 7) {
534            historySet.add(slaCalc.getId());
535            removeAndDecrement(slaCalc.getId());
536            LOG.debug("Removed Job [{0}] from map after Event-processed=7", slaCalc.getId());
537        }
538    }
539
540    public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException {
541        SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get(
542                SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId());
543
544        if (regBean.getExpectedDuration() > 0) {
545            slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration());
546        }
547        if (regBean.getExpectedEnd() != null) {
548            slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd());
549        }
550        if (regBean.getExpectedStart() != null) {
551            slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart());
552        }
553        if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) {
554            slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT,
555                    regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT));
556        }
557        if (regBean.getNominalTime() != null) {
558            slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime());
559        }
560    }
561
562    @VisibleForTesting
563    public boolean isJobIdInSLAMap(String jobId) {
564        return this.slaMap.containsKey(jobId);
565    }
566
567    @VisibleForTesting
568    public boolean isJobIdInHistorySet(String jobId) {
569        return this.historySet.contains(jobId);
570    }
571
572    private void setLogPrefix(String jobId) {
573        LOG = LogUtils.setLogInfo(LOG, jobId, null, null);
574    }
575
576    @Override
577    public boolean enableAlert(List<String> jobIds) throws JPAExecutorException, ServiceException {
578        boolean isJobFound = false;
579        @SuppressWarnings("rawtypes")
580        List<UpdateEntry> updateList = new ArrayList<BatchQueryExecutor.UpdateEntry>();
581        for (String jobId : jobIds) {
582            SLACalcStatus slaCalc = getOrCreateSLACalcStatus(jobId);
583            slaCalc.getSLARegistrationBean().removeFromSLAConfigMap(OozieClient.SLA_DISABLE_ALERT);
584            updateDBSlaConfig(slaCalc, updateList);
585            isJobFound = true;
586        }
587        executeBatchQuery(updateList);
588        return isJobFound;
589    }
590
591    @Override
592    public boolean enableChildJobAlert(List<String> parentJobIds) throws JPAExecutorException, ServiceException {
593        return enableAlert(getSLAJobsforParents(parentJobIds));
594    }
595
596    @Override
597    public boolean disableAlert(List<String> jobIds) throws JPAExecutorException, ServiceException {
598        boolean isJobFound = false;
599        @SuppressWarnings("rawtypes")
600        List<UpdateEntry> updateList = new ArrayList<BatchQueryExecutor.UpdateEntry>();
601
602        for (String jobId : jobIds) {
603            SLACalcStatus slaCalc = getOrCreateSLACalcStatus(jobId);
604            slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, Boolean.toString(true));
605            updateDBSlaConfig(slaCalc, updateList);
606            isJobFound = true;
607        }
608        executeBatchQuery(updateList);
609        return isJobFound;
610    }
611
612    @Override
613    public boolean disableChildJobAlert(List<String> parentJobIds) throws JPAExecutorException, ServiceException {
614        return disableAlert(getSLAJobsforParents(parentJobIds));
615    }
616
617    @Override
618    public boolean changeDefinition(List<Pair<String, Map<String, String>>> jobIdsSLAPair) throws JPAExecutorException,
619            ServiceException {
620        boolean isJobFound = false;
621        @SuppressWarnings("rawtypes")
622        List<UpdateEntry> updateList = new ArrayList<BatchQueryExecutor.UpdateEntry>();
623        for (Pair<String, Map<String, String>> jobIdSLAPair : jobIdsSLAPair) {
624            SLACalcStatus slaCalc = getOrCreateSLACalcStatus(jobIdSLAPair.getFirst());
625            updateParams(slaCalc, jobIdSLAPair.getSecond());
626            updateDBSlaExpectedValues(slaCalc, updateList);
627            isJobFound = true;
628        }
629        executeBatchQuery(updateList);
630        return isJobFound;
631    }
632
633    private void updateParams(SLACalcStatus slaCalc, Map<String, String> newParams) throws ServiceException {
634        SLARegistrationBean reg = slaCalc.getSLARegistrationBean();
635        if (newParams != null) {
636            try {
637                Date newNominal = SLAOperations.setNominalTime(newParams.get(RestConstants.SLA_NOMINAL_TIME), reg);
638                SLAOperations.setExpectedStart(newParams.get(RestConstants.SLA_SHOULD_START), newNominal, reg);
639                SLAOperations.setExpectedEnd(newParams.get(RestConstants.SLA_SHOULD_END), newNominal, reg);
640                SLAOperations.setExpectedDuration(newParams.get(RestConstants.SLA_MAX_DURATION), reg);
641            }
642            catch (CommandException ce) {
643                throw new ServiceException(ce);
644            }
645        }
646    }
647
648    private List<String> getSLAJobsforParents(List<String> parentJobIds) throws JPAExecutorException {
649        List<String> childJobIds = new ArrayList<String>();
650        for (String jobId : parentJobIds) {
651            List<SLARegistrationBean> registrationBeanList = SLARegistrationQueryExecutor.getInstance().getList(
652                    SLARegQuery.GET_SLA_REG_FOR_PARENT_ID, jobId);
653            for (SLARegistrationBean bean : registrationBeanList) {
654                childJobIds.add(bean.getId());
655            }
656        }
657        return childJobIds;
658    }
659
660    private boolean checkAndUpdateSLACalcAfterRestart(SLACalcStatus slaCalc) throws JPAExecutorException {
661        if (slaCalc != null && slaCalc.getSLARegistrationBean() == null) {
662            return updateSLARegistartion(slaCalc);
663        }
664        return false;
665    }
666
667    public boolean updateSLARegistartion(SLACalcStatus slaCalc) throws JPAExecutorException {
668        if (slaCalc.getSLARegistrationBean() == null) {
669            synchronized (slaCalc) {
670                if (slaCalc.getSLARegistrationBean() == null) {
671                    SLARegistrationBean slaRegBean = SLARegistrationQueryExecutor.getInstance()
672                            .get(SLARegQuery.GET_SLA_REG_ON_RESTART, slaCalc.getId());
673                    slaCalc.updateSLARegistrationBean(slaRegBean);
674                    return true;
675                }
676            }
677        }
678        return false;
679    }
680
681    private boolean putAndIncrement(final String jobId, final SLACalcStatus newStatus) {
682        if (slaMap.put(jobId, newStatus) == null) {
683            LOG.trace("Added a new item to SLA map. [jobId={0}]", jobId);
684            instrumentation.incr(INSTRUMENTATION_GROUP, SLA_MAP, 1);
685            return true;
686        }
687
688        LOG.trace("Updated an existing item in SLA map. [jobId={0}]", jobId);
689        return false;
690    }
691
692    private boolean removeAndDecrement(final String jobId) {
693        if (slaMap.remove(jobId) != null) {
694            LOG.trace("Removed an existing item from SLA map. [jobId={0}]", jobId);
695            instrumentation.decr(INSTRUMENTATION_GROUP, SLA_MAP, 1);
696            return true;
697        }
698
699        LOG.trace("Tried to remove a non-existing item from SLA map. [jobId={0}]", jobId);
700        return false;
701    }
702
703    private void resetRetryCount(final String jobId) {
704        if (slaMap.containsKey(jobId)) {
705            LOG.debug("Resetting retry count on [{0}]", jobId);
706            final SLACalcStatus existingStatus = slaMap.get(jobId);
707            existingStatus.resetRetryCount();
708            putAndIncrement(jobId, existingStatus);
709        }
710    }
711
712    private void incrementRetryCountAndRemove(final String jobId) {
713        LOG.debug("Checking SLA calculator status [{0}] for retry count", jobId);
714        if (slaMap.containsKey(jobId)) {
715            final SLACalcStatus existingStatus = slaMap.get(jobId);
716            if (existingStatus.getRetryCount() < maxRetryCount) {
717                existingStatus.incrementRetryCount();
718                LOG.debug("Retrying with SLA calculator status [{0}] retry count [{1}]", jobId, existingStatus.getRetryCount());
719                putAndIncrement(jobId, existingStatus);
720            }
721            else {
722                LOG.debug("Removing [{0}] from SLA map as maximum retry count reached", jobId);
723                removeAndDecrement(jobId);
724            }
725        }
726    }
727}