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