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.command.coord;
020
021import org.apache.commons.lang.StringUtils;
022import org.apache.hadoop.conf.Configuration;
023import org.apache.oozie.AppType;
024import org.apache.oozie.CoordinatorActionBean;
025import org.apache.oozie.CoordinatorJobBean;
026import org.apache.oozie.ErrorCode;
027import org.apache.oozie.SLAEventBean;
028import org.apache.oozie.client.CoordinatorJob;
029import org.apache.oozie.client.Job;
030import org.apache.oozie.client.SLAEvent.SlaAppType;
031import org.apache.oozie.client.rest.JsonBean;
032import org.apache.oozie.command.CommandException;
033import org.apache.oozie.command.MaterializeTransitionXCommand;
034import org.apache.oozie.command.PreconditionException;
035import org.apache.oozie.command.bundle.BundleStatusUpdateXCommand;
036import org.apache.oozie.coord.CoordUtils;
037import org.apache.oozie.coord.TimeUnit;
038import org.apache.oozie.coord.input.logic.CoordInputLogicEvaluatorUtil;
039import org.apache.oozie.executor.jpa.BatchQueryExecutor;
040import org.apache.oozie.executor.jpa.BatchQueryExecutor.UpdateEntry;
041import org.apache.oozie.executor.jpa.CoordActionsActiveCountJPAExecutor;
042import org.apache.oozie.executor.jpa.CoordJobQueryExecutor;
043import org.apache.oozie.executor.jpa.CoordJobQueryExecutor.CoordJobQuery;
044import org.apache.oozie.executor.jpa.JPAExecutorException;
045import org.apache.oozie.service.ConfigurationService;
046import org.apache.oozie.service.CoordMaterializeTriggerService;
047import org.apache.oozie.service.EventHandlerService;
048import org.apache.oozie.service.JPAService;
049import org.apache.oozie.service.Service;
050import org.apache.oozie.service.Services;
051import org.apache.oozie.sla.SLAOperations;
052import org.apache.oozie.util.DateUtils;
053import org.apache.oozie.util.Instrumentation;
054import org.apache.oozie.util.LogUtils;
055import org.apache.oozie.util.ParamChecker;
056import org.apache.oozie.util.StatusUtils;
057import org.apache.oozie.util.XConfiguration;
058import org.apache.oozie.util.XmlUtils;
059import org.apache.oozie.util.db.SLADbOperations;
060import org.jdom.Element;
061import org.jdom.JDOMException;
062
063import java.io.IOException;
064import java.io.StringReader;
065import java.sql.Timestamp;
066import java.util.Calendar;
067import java.util.Date;
068import java.util.TimeZone;
069
070/**
071 * Materialize actions for specified start and end time for coordinator job.
072 */
073@SuppressWarnings("deprecation")
074public class CoordMaterializeTransitionXCommand extends MaterializeTransitionXCommand {
075
076    private JPAService jpaService = null;
077    private CoordinatorJobBean coordJob = null;
078    private String jobId = null;
079    private Date startMatdTime = null;
080    private Date endMatdTime = null;
081    private final int materializationWindow;
082    private int lastActionNumber = 1; // over-ride by DB value
083    private CoordinatorJob.Status prevStatus = null;
084
085    static final private int lookAheadWindow = ConfigurationService.getInt(CoordMaterializeTriggerService
086            .CONF_LOOKUP_INTERVAL);
087
088    /**
089     * Default MAX timeout in minutes, after which coordinator input check will timeout
090     */
091    public static final String CONF_DEFAULT_MAX_TIMEOUT = Service.CONF_PREFIX + "coord.default.max.timeout";
092
093    /**
094     * The constructor for class {@link CoordMaterializeTransitionXCommand}
095     *
096     * @param jobId coordinator job id
097     * @param materializationWindow materialization window to calculate end time
098     */
099    public CoordMaterializeTransitionXCommand(String jobId, int materializationWindow) {
100        super("coord_mater", "coord_mater", 1);
101        this.jobId = ParamChecker.notEmpty(jobId, "jobId");
102        this.materializationWindow = materializationWindow;
103    }
104
105    public CoordMaterializeTransitionXCommand(CoordinatorJobBean coordJob, int materializationWindow, Date startTime,
106                                              Date endTime) {
107        super("coord_mater", "coord_mater", 1);
108        this.jobId = ParamChecker.notEmpty(coordJob.getId(), "jobId");
109        this.materializationWindow = materializationWindow;
110        this.coordJob = coordJob;
111        this.startMatdTime = startTime;
112        this.endMatdTime = endTime;
113    }
114
115    /* (non-Javadoc)
116     * @see org.apache.oozie.command.MaterializeTransitionXCommand#transitToNext()
117     */
118    @Override
119    public void transitToNext() throws CommandException {
120    }
121
122    /* (non-Javadoc)
123     * @see org.apache.oozie.command.TransitionXCommand#updateJob()
124     */
125    @Override
126    public void updateJob() throws CommandException {
127        updateList.add(new UpdateEntry(CoordJobQuery.UPDATE_COORD_JOB_MATERIALIZE,coordJob));
128    }
129
130    /* (non-Javadoc)
131     * @see org.apache.oozie.command.MaterializeTransitionXCommand#performWrites()
132     */
133    @Override
134    public void performWrites() throws CommandException {
135        try {
136            BatchQueryExecutor.getInstance().executeBatchInsertUpdateDelete(insertList, updateList, null);
137            // register the partition related dependencies of actions
138            for (JsonBean actionBean : insertList) {
139                if (actionBean instanceof CoordinatorActionBean) {
140                    CoordinatorActionBean coordAction = (CoordinatorActionBean) actionBean;
141                    if (EventHandlerService.isEnabled()) {
142                        CoordinatorXCommand.generateEvent(coordAction, coordJob.getUser(), coordJob.getAppName(), null);
143                    }
144
145                    // TODO: time 100s should be configurable
146                    queue(new CoordActionNotificationXCommand(coordAction), 100);
147
148                    //Delay for input check = (nominal time - now)
149                    long checkDelay = coordAction.getNominalTime().getTime() - new Date().getTime();
150                    queue(new CoordActionInputCheckXCommand(coordAction.getId(), coordAction.getJobId()),
151                        Math.max(checkDelay, 0));
152
153                    if (!StringUtils.isEmpty(coordAction.getPushMissingDependencies())) {
154                        // TODO: Delay in catchup mode?
155                        queue(new CoordPushDependencyCheckXCommand(coordAction.getId(), true), 100);
156                    }
157                }
158            }
159        }
160        catch (JPAExecutorException jex) {
161            throw new CommandException(jex);
162        }
163    }
164
165    /* (non-Javadoc)
166     * @see org.apache.oozie.command.XCommand#getEntityKey()
167     */
168    @Override
169    public String getEntityKey() {
170        return this.jobId;
171    }
172
173    @Override
174    protected boolean isLockRequired() {
175        return true;
176    }
177
178    /* (non-Javadoc)
179     * @see org.apache.oozie.command.XCommand#loadState()
180     */
181    @Override
182    protected void loadState() throws CommandException {
183        jpaService = Services.get().get(JPAService.class);
184        if (jpaService == null) {
185            LOG.error(ErrorCode.E0610);
186        }
187
188        try {
189            coordJob = CoordJobQueryExecutor.getInstance().get(CoordJobQuery.GET_COORD_JOB_MATERIALIZE, jobId);
190            prevStatus = coordJob.getStatus();
191        }
192        catch (JPAExecutorException jex) {
193            throw new CommandException(jex);
194        }
195
196        // calculate start materialize and end materialize time
197        calcMatdTime();
198
199        LogUtils.setLogInfo(coordJob);
200    }
201
202    /**
203     * Calculate startMatdTime and endMatdTime from job's start time if next materialized time is null
204     *
205     * @throws CommandException thrown if failed to calculate startMatdTime and endMatdTime
206     */
207    protected void calcMatdTime() throws CommandException {
208        Timestamp startTime = coordJob.getNextMaterializedTimestamp();
209        if (startTime == null) {
210            startTime = coordJob.getStartTimestamp();
211        }
212        // calculate end time by adding materializationWindow to start time.
213        // need to convert materializationWindow from secs to milliseconds
214        long startTimeMilli = startTime.getTime();
215        long endTimeMilli = startTimeMilli + (materializationWindow * 1000);
216
217        startMatdTime = DateUtils.toDate(new Timestamp(startTimeMilli));
218        endMatdTime = DateUtils.toDate(new Timestamp(endTimeMilli));
219        endMatdTime = getMaterializationTimeForCatchUp(endMatdTime);
220        // if MaterializationWindow end time is greater than endTime
221        // for job, then set it to endTime of job
222        Date jobEndTime = coordJob.getEndTime();
223        if (endMatdTime.compareTo(jobEndTime) > 0) {
224            endMatdTime = jobEndTime;
225        }
226
227        LOG.debug("Materializing coord job id=" + jobId + ", start=" + DateUtils.formatDateOozieTZ(startMatdTime) + ", end="
228                + DateUtils.formatDateOozieTZ(endMatdTime)
229                + ", window=" + materializationWindow);
230    }
231
232    /**
233     * Get materialization for window for catch-up jobs. for current jobs,it reruns currentMatdate, For catch-up, end
234     * Mataterilized Time = startMatdTime + MatThrottling * frequency; unless LAST_ONLY execution order is set, in which
235     * case it returns now (to materialize all actions in the past)
236     *
237     * @param currentMatTime
238     * @return Date returns materialization for window for catch-up jobs
239     * @throws CommandException
240     * @throws JDOMException
241     */
242    private Date getMaterializationTimeForCatchUp(Date currentMatTime) throws CommandException {
243        if (currentMatTime.after(new Date())) {
244            return currentMatTime;
245        }
246        if (coordJob.getExecutionOrder().equals(CoordinatorJob.Execution.LAST_ONLY) ||
247                coordJob.getExecutionOrder().equals(CoordinatorJob.Execution.NONE)) {
248            return new Date();
249        }
250        final int frequency;
251        try {
252            frequency = Integer.parseInt(coordJob.getFrequency());
253        }
254        catch (final NumberFormatException e) {
255            // Cron based frequency: catching up at maximum till the coordinator job's end time,
256            // bounded also by the throttle parameter, aka the number of coordinator actions to materialize
257            return coordJob.getEndTime();
258        }
259
260        TimeZone appTz = DateUtils.getTimeZone(coordJob.getTimeZone());
261        TimeUnit freqTU = TimeUnit.valueOf(coordJob.getTimeUnitStr());
262        Calendar startInstance = Calendar.getInstance(appTz);
263        startInstance.setTime(startMatdTime);
264        Calendar endMatInstance = null;
265        Calendar previousInstance = startInstance;
266        for (int i = 1; i <= coordJob.getMatThrottling(); i++) {
267            endMatInstance = (Calendar) startInstance.clone();
268            endMatInstance.add(freqTU.getCalendarUnit(), i * frequency);
269            if (endMatInstance.getTime().compareTo(new Date()) >= 0) {
270                if (previousInstance.getTime().after(currentMatTime)) {
271                    return previousInstance.getTime();
272                }
273                else {
274                    return currentMatTime;
275                }
276            }
277            previousInstance = endMatInstance;
278        }
279        if (endMatInstance == null) {
280            return currentMatTime;
281        }
282        else {
283            return endMatInstance.getTime();
284        }
285    }
286
287    /* (non-Javadoc)
288     * @see org.apache.oozie.command.XCommand#verifyPrecondition()
289     */
290    @Override
291    protected void verifyPrecondition() throws CommandException, PreconditionException {
292        if (!(coordJob.getStatus() == CoordinatorJobBean.Status.PREP || coordJob.getStatus() == CoordinatorJobBean.Status.RUNNING
293                || coordJob.getStatus() == CoordinatorJobBean.Status.RUNNINGWITHERROR)) {
294            throw new PreconditionException(ErrorCode.E1100, "CoordMaterializeTransitionXCommand for jobId=" + jobId
295                    + " job is not in PREP or RUNNING but in " + coordJob.getStatus());
296        }
297
298        if (coordJob.isDoneMaterialization()) {
299            throw new PreconditionException(ErrorCode.E1100, "CoordMaterializeTransitionXCommand for jobId =" + jobId
300                    + " job is already materialized");
301        }
302
303        if (coordJob.getNextMaterializedTimestamp() != null
304                && coordJob.getNextMaterializedTimestamp().compareTo(coordJob.getEndTimestamp()) >= 0) {
305            throw new PreconditionException(ErrorCode.E1100, "CoordMaterializeTransitionXCommand for jobId=" + jobId
306                    + " job is already materialized");
307        }
308
309        Timestamp startTime = coordJob.getNextMaterializedTimestamp();
310        if (startTime == null) {
311            startTime = coordJob.getStartTimestamp();
312
313            if (startTime.after(new Timestamp(System.currentTimeMillis() + lookAheadWindow * 1000))) {
314                throw new PreconditionException(ErrorCode.E1100, "CoordMaterializeTransitionXCommand for jobId="
315                        + jobId + " job's start time is not reached yet - nothing to materialize");
316            }
317        }
318
319        if (coordJob.getNextMaterializedTimestamp() != null
320                && coordJob.getNextMaterializedTimestamp().after(
321                        new Timestamp(System.currentTimeMillis() + lookAheadWindow * 1000))) {
322            throw new PreconditionException(ErrorCode.E1100, "CoordMaterializeTransitionXCommand for jobId=" + jobId
323                    + " Request is for future time. Lookup time is  "
324                    + new Timestamp(System.currentTimeMillis() + lookAheadWindow * 1000) + " mat time is "
325                    + coordJob.getNextMaterializedTimestamp());
326        }
327
328        if (coordJob.getLastActionTime() != null && coordJob.getLastActionTime().compareTo(coordJob.getEndTime()) >= 0) {
329            throw new PreconditionException(ErrorCode.E1100, "ENDED Coordinator materialization for jobId = " + jobId
330                    + ", all actions have been materialized from start time = " + coordJob.getStartTime()
331                    + " to end time = " + coordJob.getEndTime() + ", job status = " + coordJob.getStatusStr());
332        }
333
334        if (coordJob.getLastActionTime() != null && coordJob.getLastActionTime().compareTo(endMatdTime) >= 0) {
335            throw new PreconditionException(ErrorCode.E1100, "ENDED Coordinator materialization for jobId = " + jobId
336                    + ", action is *already* materialized for Materialization start time = " + startMatdTime
337                    + ", materialization end time = " + endMatdTime + ", job status = " + coordJob.getStatusStr());
338        }
339
340        if (endMatdTime.after(coordJob.getEndTime())) {
341            throw new PreconditionException(ErrorCode.E1100, "ENDED Coordinator materialization for jobId = " + jobId
342                    + " materialization end time = " + endMatdTime + " surpasses coordinator job's end time = "
343                    + coordJob.getEndTime() + " job status = " + coordJob.getStatusStr());
344        }
345
346        if (coordJob.getPauseTime() != null && !startMatdTime.before(coordJob.getPauseTime())) {
347            throw new PreconditionException(ErrorCode.E1100, "ENDED Coordinator materialization for jobId = " + jobId
348                    + ", materialization start time = " + startMatdTime
349                    + " is after or equal to coordinator job's pause time = " + coordJob.getPauseTime()
350                    + ", job status = " + coordJob.getStatusStr());
351        }
352
353    }
354
355    /* (non-Javadoc)
356     * @see org.apache.oozie.command.MaterializeTransitionXCommand#materialize()
357     */
358    @Override
359    protected void materialize() throws CommandException {
360        Instrumentation.Cron cron = new Instrumentation.Cron();
361        cron.start();
362        try {
363            materializeActions(false);
364            updateJobMaterializeInfo(coordJob);
365        }
366        catch (CommandException ex) {
367            LOG.warn("Exception occurred:" + ex.getMessage() + " Making the job failed ", ex);
368            coordJob.setStatus(Job.Status.FAILED);
369            coordJob.resetPending();
370            // remove any materialized actions and slaEvents
371            insertList.clear();
372        }
373        catch (Exception e) {
374            LOG.error("Exception occurred:" + e.getMessage() + " Making the job failed ", e);
375            coordJob.setStatus(Job.Status.FAILED);
376            try {
377                CoordJobQueryExecutor.getInstance().executeUpdate(CoordJobQuery.UPDATE_COORD_JOB_MATERIALIZE, coordJob);
378            }
379            catch (JPAExecutorException jex) {
380                throw new CommandException(ErrorCode.E1011, jex);
381            }
382            throw new CommandException(ErrorCode.E1012, e.getMessage(), e);
383        } finally {
384            cron.stop();
385            instrumentation.addCron(INSTRUMENTATION_GROUP, getName() + ".materialize", cron);
386        }
387    }
388
389    /**
390     * Create action instances starting from "startMatdTime" to "endMatdTime" and store them into coord action table.
391     *
392     * @param dryrun if this is a dry run
393     * @throws Exception thrown if failed to materialize actions
394     */
395    protected String materializeActions(boolean dryrun) throws Exception {
396
397        Configuration jobConf = null;
398        try {
399            jobConf = new XConfiguration(new StringReader(coordJob.getConf()));
400        }
401        catch (IOException ioe) {
402            LOG.warn("Configuration parse error. read from DB :" + coordJob.getConf(), ioe);
403            throw new CommandException(ErrorCode.E1005, ioe.getMessage(), ioe);
404        }
405
406        String jobXml = coordJob.getJobXml();
407        Element eJob = XmlUtils.parseXml(jobXml);
408        TimeZone appTz = DateUtils.getTimeZone(coordJob.getTimeZone());
409
410        String frequency = coordJob.getFrequency();
411        TimeUnit freqTU = TimeUnit.valueOf(coordJob.getTimeUnitStr());
412        TimeUnit endOfFlag = TimeUnit.valueOf(eJob.getAttributeValue("end_of_duration"));
413        Calendar start = Calendar.getInstance(appTz);
414        start.setTime(startMatdTime);
415        DateUtils.moveToEnd(start, endOfFlag);
416        Calendar end = Calendar.getInstance(appTz);
417        end.setTime(endMatdTime);
418        lastActionNumber = coordJob.getLastActionNumber();
419        //Intentionally printing dates in their own timezone, not Oozie timezone
420        LOG.info("materialize actions for tz=" + appTz.getDisplayName() + ",\n start=" + start.getTime() + ", end="
421                + end.getTime() + ",\n timeUnit " + freqTU.getCalendarUnit() + ",\n frequency :" + frequency + ":"
422                + freqTU + ",\n lastActionNumber " + lastActionNumber);
423        // Keep the actual start time
424        Calendar origStart = Calendar.getInstance(appTz);
425        origStart.setTime(coordJob.getStartTimestamp());
426        // Move to the End of duration, if needed.
427        DateUtils.moveToEnd(origStart, endOfFlag);
428
429        StringBuilder actionStrings = new StringBuilder();
430        Date jobPauseTime = coordJob.getPauseTime();
431        Calendar pause = null;
432        if (jobPauseTime != null) {
433            pause = Calendar.getInstance(appTz);
434            pause.setTime(DateUtils.convertDateToTimestamp(jobPauseTime));
435        }
436
437        String action = null;
438        int numWaitingActions = dryrun ? 0 : jpaService.execute(new CoordActionsActiveCountJPAExecutor(coordJob.getId()));
439        int maxActionToBeCreated = coordJob.getMatThrottling() - numWaitingActions;
440        // If LAST_ONLY and all materialization is in the past, ignore maxActionsToBeCreated
441        boolean ignoreMaxActions =
442                (coordJob.getExecutionOrder().equals(CoordinatorJob.Execution.LAST_ONLY) ||
443                        coordJob.getExecutionOrder().equals(CoordinatorJob.Execution.NONE))
444                        && endMatdTime.before(new Date());
445        LOG.debug("Coordinator job :" + coordJob.getId() + ", maxActionToBeCreated :" + maxActionToBeCreated
446                + ", Mat_Throttle :" + coordJob.getMatThrottling() + ", numWaitingActions :" + numWaitingActions);
447
448        boolean isCronFrequency = false;
449
450        Calendar effStart = (Calendar) start.clone();
451        try {
452            int intFrequency = Integer.parseInt(coordJob.getFrequency());
453            effStart = (Calendar) origStart.clone();
454            effStart.add(freqTU.getCalendarUnit(), lastActionNumber * intFrequency);
455        }
456        catch (NumberFormatException e) {
457            isCronFrequency = true;
458        }
459
460        boolean firstMater = true;
461        while (effStart.compareTo(end) < 0 && (ignoreMaxActions || maxActionToBeCreated-- > 0)) {
462            if (pause != null && effStart.compareTo(pause) >= 0) {
463                break;
464            }
465
466            Date nextTime = effStart.getTime();
467
468            if (isCronFrequency) {
469                if (effStart.getTime().compareTo(startMatdTime) == 0 && firstMater) {
470                    effStart.add(Calendar.MINUTE, -1);
471                    firstMater = false;
472                }
473                nextTime = CoordCommandUtils.getNextValidActionTimeForCronFrequency(effStart.getTime(), coordJob);
474                Date prevTime = new Date(effStart.getTimeInMillis());
475                effStart.setTime(nextTime);
476                addDSTChangeToNominalTime(prevTime, nextTime, coordJob);
477            }
478
479            if (effStart.compareTo(end) < 0) {
480
481                if (pause != null && effStart.compareTo(pause) >= 0) {
482                    break;
483                }
484                CoordinatorActionBean actionBean = new CoordinatorActionBean();
485                lastActionNumber++;
486
487                int timeout = coordJob.getTimeout();
488                LOG.debug("Materializing action for time=" + DateUtils.formatDateOozieTZ(effStart.getTime())
489                        + ", lastactionnumber=" + lastActionNumber + " timeout=" + timeout + " minutes");
490                Date actualTime = new Date();
491                action = CoordCommandUtils.materializeOneInstance(jobId, dryrun, (Element) eJob.clone(),
492                        nextTime, actualTime, lastActionNumber, jobConf, actionBean);
493                actionBean.setTimeOut(timeout);
494                if (!dryrun) {
495                    storeToDB(actionBean, action, jobConf); // Storing to table
496
497                }
498                else {
499                    actionStrings.append("action for new instance");
500                    actionStrings.append(action);
501                }
502            }
503            else {
504                break;
505            }
506
507            if (!isCronFrequency) {
508                effStart = (Calendar) origStart.clone();
509                effStart.add(freqTU.getCalendarUnit(), lastActionNumber * Integer.parseInt(coordJob.getFrequency()));
510            }
511        }
512
513        if (isCronFrequency) {
514            if (effStart.compareTo(end) < 0 && !(ignoreMaxActions || maxActionToBeCreated-- > 0)) {
515                //Since we exceed the throttle, we need to move the nextMadtime forward
516                //to avoid creating duplicate actions
517                if (!firstMater) {
518                    effStart.setTime(CoordCommandUtils.getNextValidActionTimeForCronFrequency(effStart.getTime(), coordJob));
519                }
520            }
521        }
522
523        endMatdTime = effStart.getTime();
524
525        if (!dryrun) {
526            return action;
527        }
528        else {
529            return actionStrings.toString();
530        }
531    }
532
533    /**
534     * Apply DST correction according the job`s timezone, if the difference between the previous nominal time and the actual one
535     * is greater or equal than 24 hours.
536     * Calendar uses a similar approach: applies DST change if the TimeUnit is lower or equal than TimeUnit.DAY. With this approach
537     * a similar behaviour can be achieved.
538     *
539     * @see {@http://oozie.apache.org/docs/5.0.0/CoordinatorFunctionalSpec.html#a7._Handling_Timezones_and_Daylight_Saving_Time}
540     *
541     * @param prevTime nominal time of the previous coordinator action
542     * @param nextTime nominal time of the actual coordinator action
543     * @param coordJob the coordinator job
544     */
545    private void addDSTChangeToNominalTime(Date prevTime, Date nextTime, CoordinatorJobBean coordJob) {
546        final long differenceBetweenTwoActionsInSec = java.util.concurrent.TimeUnit.MILLISECONDS.toSeconds
547                (Math.abs(prevTime.getTime() - nextTime.getTime()));
548        final long oneDayInSeconds = java.util.concurrent.TimeUnit.DAYS.toSeconds(1);
549        if (differenceBetweenTwoActionsInSec < oneDayInSeconds) {
550            return;
551        }
552        final long dstOffset = DaylightOffsetCalculator.getDSTOffset(DateUtils
553                .getTimeZone(coordJob.getTimeZone()), coordJob.getStartTime(), nextTime);
554        LOG.debug("[{0}] ms DST offset applied to nominal time for coordinator job: [{1}]", dstOffset, coordJob.getId());
555        nextTime.setTime(nextTime.getTime() + dstOffset);
556    }
557
558    private void storeToDB(CoordinatorActionBean actionBean, String actionXml, Configuration jobConf) throws Exception {
559        LOG.debug("In storeToDB() coord action id = " + actionBean.getId() + ", size of actionXml = "
560                + actionXml.length());
561        actionBean.setActionXml(actionXml);
562        insertList.add(actionBean);
563        writeActionSlaRegistration(actionXml, actionBean, jobConf);
564    }
565
566    private void writeActionSlaRegistration(String actionXml, CoordinatorActionBean actionBean, Configuration jobConf)
567            throws Exception {
568        Element eAction = XmlUtils.parseXml(actionXml);
569        Element eSla = eAction.getChild("action", eAction.getNamespace()).getChild("info", eAction.getNamespace("sla"));
570                SLAEventBean slaEvent = SLADbOperations.createSlaRegistrationEvent(eSla, actionBean.getId(),
571                                 SlaAppType.COORDINATOR_ACTION, coordJob.getUser(), coordJob.getGroup(), LOG);
572                         if (slaEvent != null) {
573            insertList.add(slaEvent);
574        }
575        // inserting into new table also
576        SLAOperations.createSlaRegistrationEvent(eSla, actionBean.getId(), actionBean.getJobId(),
577                AppType.COORDINATOR_ACTION, coordJob.getUser(), coordJob.getAppName(), LOG, false,
578                CoordUtils.isSlaAlertDisabled(actionBean, coordJob.getAppName(), jobConf));
579    }
580
581    private void updateJobMaterializeInfo(CoordinatorJobBean job) throws CommandException {
582        job.setLastActionTime(endMatdTime);
583        job.setLastActionNumber(lastActionNumber);
584        // if the job endtime == action endtime, we don't need to materialize this job anymore
585        Date jobEndTime = job.getEndTime();
586
587        if (job.getStatus() == CoordinatorJob.Status.PREP){
588            LOG.info("[" + job.getId() + "]: Update status from " + job.getStatus() + " to RUNNING");
589            job.setStatus(Job.Status.RUNNING);
590        }
591        job.setPending();
592
593        if (jobEndTime.compareTo(endMatdTime) <= 0) {
594            LOG.info("[" + job.getId() + "]: all actions have been materialized, set pending to true");
595            // set doneMaterialization to true when materialization is done
596            job.setDoneMaterialization();
597        }
598        job.setStatus(StatusUtils.getStatus(job));
599        LOG.info("Coord Job status updated to = " + job.getStatus());
600        job.setNextMaterializedTime(endMatdTime);
601    }
602
603    /* (non-Javadoc)
604     * @see org.apache.oozie.command.XCommand#getKey()
605     */
606    @Override
607    public String getKey() {
608        return getName() + "_" + jobId;
609    }
610
611    /* (non-Javadoc)
612     * @see org.apache.oozie.command.TransitionXCommand#notifyParent()
613     */
614    @Override
615    public void notifyParent() throws CommandException {
616        // update bundle action only when status changes in coord job
617        if (this.coordJob.getBundleId() != null) {
618            if (!prevStatus.equals(coordJob.getStatus())) {
619                BundleStatusUpdateXCommand bundleStatusUpdate = new BundleStatusUpdateXCommand(coordJob, prevStatus);
620                bundleStatusUpdate.call();
621            }
622        }
623    }
624}