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.wf;
020
021import java.util.ArrayList;
022import java.util.Date;
023import java.util.List;
024
025import org.apache.hadoop.conf.Configuration;
026import org.apache.oozie.DagELFunctions;
027import org.apache.oozie.ErrorCode;
028import org.apache.oozie.SLAEventBean;
029import org.apache.oozie.WorkflowActionBean;
030import org.apache.oozie.WorkflowJobBean;
031import org.apache.oozie.XException;
032import org.apache.oozie.action.ActionExecutor;
033import org.apache.oozie.action.ActionExecutorException;
034import org.apache.oozie.action.control.ControlNodeActionExecutor;
035import org.apache.oozie.client.OozieClient;
036import org.apache.oozie.client.WorkflowAction;
037import org.apache.oozie.client.WorkflowJob;
038import org.apache.oozie.client.SLAEvent.SlaAppType;
039import org.apache.oozie.client.SLAEvent.Status;
040import org.apache.oozie.client.rest.JsonBean;
041import org.apache.oozie.command.CommandException;
042import org.apache.oozie.command.PreconditionException;
043import org.apache.oozie.executor.jpa.BatchQueryExecutor.UpdateEntry;
044import org.apache.oozie.executor.jpa.BatchQueryExecutor;
045import org.apache.oozie.executor.jpa.JPAExecutorException;
046import org.apache.oozie.executor.jpa.WorkflowActionQueryExecutor;
047import org.apache.oozie.executor.jpa.WorkflowJobQueryExecutor;
048import org.apache.oozie.executor.jpa.WorkflowActionQueryExecutor.WorkflowActionQuery;
049import org.apache.oozie.executor.jpa.WorkflowJobQueryExecutor.WorkflowJobQuery;
050import org.apache.oozie.service.ActionService;
051import org.apache.oozie.service.EventHandlerService;
052import org.apache.oozie.service.JPAService;
053import org.apache.oozie.service.Services;
054import org.apache.oozie.service.UUIDService;
055import org.apache.oozie.util.Instrumentation;
056import org.apache.oozie.util.LogUtils;
057import org.apache.oozie.util.StringUtils;
058import org.apache.oozie.util.XLog;
059import org.apache.oozie.util.db.SLADbXOperations;
060import org.apache.oozie.workflow.WorkflowInstance;
061
062@SuppressWarnings("deprecation")
063public class ActionEndXCommand extends ActionXCommand<Void> {
064    public static final String COULD_NOT_END = "COULD_NOT_END";
065    public static final String END_DATA_MISSING = "END_DATA_MISSING";
066
067    private String jobId = null;
068    private String actionId = null;
069    private WorkflowJobBean wfJob = null;
070    private WorkflowActionBean wfAction = null;
071    private JPAService jpaService = null;
072    private ActionExecutor executor = null;
073    private List<UpdateEntry> updateList = new ArrayList<UpdateEntry>();
074    private List<JsonBean> insertList = new ArrayList<JsonBean>();
075
076    public ActionEndXCommand(String actionId, String type) {
077        super("action.end", type, 0);
078        this.actionId = StringUtils.intern(actionId);
079        this.jobId = Services.get().get(UUIDService.class).getId(actionId);
080    }
081
082    @Override
083    protected void setLogInfo() {
084        LogUtils.setLogInfo(actionId);
085    }
086
087    @Override
088    protected boolean isLockRequired() {
089        return true;
090    }
091
092    @Override
093    public String getEntityKey() {
094        return this.jobId;
095    }
096
097    @Override
098    public String getKey() {
099        return getName() + "_" + actionId;
100    }
101
102    @Override
103    protected void loadState() throws CommandException {
104        try {
105            jpaService = Services.get().get(JPAService.class);
106            if (jpaService != null) {
107                this.wfJob = WorkflowJobQueryExecutor.getInstance().get(WorkflowJobQuery.GET_WORKFLOW_ACTION_OP,
108                        jobId);
109                this.wfAction = WorkflowActionQueryExecutor.getInstance().get(WorkflowActionQuery.GET_ACTION_END,
110                        actionId);
111                LogUtils.setLogInfo(wfJob);
112                LogUtils.setLogInfo(wfAction);
113            }
114            else {
115                throw new CommandException(ErrorCode.E0610);
116            }
117        }
118        catch (XException ex) {
119            throw new CommandException(ex);
120        }
121    }
122
123    @Override
124    protected void verifyPrecondition() throws CommandException, PreconditionException {
125        if (wfJob == null) {
126            throw new PreconditionException(ErrorCode.E0604, jobId);
127        }
128        if (wfAction == null) {
129            throw new PreconditionException(ErrorCode.E0605, actionId);
130        }
131        if (wfAction.isPending()
132                && (wfAction.getStatus() == WorkflowActionBean.Status.DONE
133                        || wfAction.getStatus() == WorkflowActionBean.Status.END_RETRY || wfAction.getStatus()
134                        == WorkflowActionBean.Status.END_MANUAL)) {
135
136            if (wfJob.getStatus() != WorkflowJob.Status.RUNNING) {
137                throw new PreconditionException(ErrorCode.E0811,  WorkflowJob.Status.RUNNING.toString());
138            }
139        }
140        else {
141            throw new PreconditionException(ErrorCode.E0812, wfAction.isPending(), wfAction.getStatusStr());
142        }
143
144        executor = Services.get().get(ActionService.class).getExecutor(wfAction.getType());
145        if (executor == null) {
146            throw new CommandException(ErrorCode.E0802, wfAction.getType());
147        }
148    }
149
150    @Override
151    protected Void execute() throws CommandException {
152        LOG.debug("STARTED ActionEndXCommand for action " + actionId);
153
154        Configuration conf = wfJob.getWorkflowInstance().getConf();
155
156        int maxRetries = 0;
157        long retryInterval = 0;
158
159        if (!(executor instanceof ControlNodeActionExecutor)) {
160            maxRetries = conf.getInt(OozieClient.ACTION_MAX_RETRIES, executor.getMaxRetries());
161            retryInterval = conf.getLong(OozieClient.ACTION_RETRY_INTERVAL, executor.getRetryInterval());
162        }
163
164        executor.setMaxRetries(maxRetries);
165        executor.setRetryInterval(retryInterval);
166
167        boolean isRetry = false;
168        if (wfAction.getStatus() == WorkflowActionBean.Status.END_RETRY
169                || wfAction.getStatus() == WorkflowActionBean.Status.END_MANUAL) {
170            isRetry = true;
171        }
172        boolean isUserRetry = false;
173        ActionExecutorContext context = new ActionXCommand.ActionExecutorContext(wfJob, wfAction, isRetry, isUserRetry);
174        try {
175
176            LOG.debug(
177                    "End, name [{0}] type [{1}] status[{2}] external status [{3}] signal value [{4}]",
178                    wfAction.getName(), wfAction.getType(), wfAction.getStatus(), wfAction.getExternalStatus(),
179                    wfAction.getSignalValue());
180
181            Instrumentation.Cron cron = new Instrumentation.Cron();
182            cron.start();
183            executor.end(context, wfAction);
184            cron.stop();
185            addActionCron(wfAction.getType(), cron);
186
187            incrActionCounter(wfAction.getType(), 1);
188
189            if (!context.isEnded()) {
190                LOG.warn(XLog.OPS, "Action Ended, ActionExecutor [{0}] must call setEndData()",
191                        executor.getType());
192                wfAction.setErrorInfo(END_DATA_MISSING, "Execution Ended, but End Data Missing from Action");
193                failJob(context);
194            } else {
195                wfAction.setRetries(0);
196                wfAction.setEndTime(new Date());
197
198                boolean shouldHandleUserRetry = false;
199                Status slaStatus = null;
200                switch (wfAction.getStatus()) {
201                    case OK:
202                        slaStatus = Status.SUCCEEDED;
203                        break;
204                    case KILLED:
205                        slaStatus = Status.KILLED;
206                        break;
207                    case FAILED:
208                        slaStatus = Status.FAILED;
209                        shouldHandleUserRetry = true;
210                        break;
211                    case ERROR:
212                        LOG.info("ERROR is considered as FAILED for SLA");
213                        slaStatus = Status.KILLED;
214                        shouldHandleUserRetry = true;
215                        break;
216                    default:
217                        slaStatus = Status.FAILED;
218                        shouldHandleUserRetry = true;
219                        break;
220                }
221                if (!shouldHandleUserRetry || !handleUserRetry(context, wfAction)) {
222                    SLAEventBean slaEvent = SLADbXOperations.createStatusEvent(wfAction.getSlaXml(), wfAction.getId(), slaStatus,
223                            SlaAppType.WORKFLOW_ACTION);
224                    if(slaEvent != null) {
225                        insertList.add(slaEvent);
226                    }
227                }
228            }
229            WorkflowInstance wfInstance = wfJob.getWorkflowInstance();
230            DagELFunctions.setActionInfo(wfInstance, wfAction);
231            wfJob.setWorkflowInstance(wfInstance);
232
233            updateList.add(new UpdateEntry<WorkflowActionQuery>(WorkflowActionQuery.UPDATE_ACTION_END,wfAction));
234            wfJob.setLastModifiedTime(new Date());
235            updateList.add(new UpdateEntry<WorkflowJobQuery>(WorkflowJobQuery.UPDATE_WORKFLOW_STATUS_INSTANCE_MODIFIED, wfJob));
236        }
237        catch (ActionExecutorException ex) {
238            LOG.warn(
239                    "Error ending action [{0}]. ErrorType [{1}], ErrorCode [{2}], Message [{3}]",
240                    wfAction.getName(), ex.getErrorType(), ex.getErrorCode(), ex.getMessage());
241            wfAction.setErrorInfo(ex.getErrorCode(), ex.getMessage());
242            wfAction.setEndTime(null);
243
244            switch (ex.getErrorType()) {
245                case TRANSIENT:
246                    if (!handleTransient(context, executor, WorkflowAction.Status.END_RETRY)) {
247                        handleNonTransient(context, executor, WorkflowAction.Status.END_MANUAL);
248                        wfAction.setPendingAge(new Date());
249                        wfAction.setRetries(0);
250                    }
251                    wfAction.setEndTime(null);
252                    break;
253                case NON_TRANSIENT:
254                    handleNonTransient(context, executor, WorkflowAction.Status.END_MANUAL);
255                    wfAction.setEndTime(null);
256                    break;
257                case ERROR:
258                    handleError(context, executor, COULD_NOT_END, false, WorkflowAction.Status.ERROR);
259                    break;
260                case FAILED:
261                    failJob(context);
262                    break;
263            }
264
265            WorkflowInstance wfInstance = wfJob.getWorkflowInstance();
266            DagELFunctions.setActionInfo(wfInstance, wfAction);
267            wfJob.setWorkflowInstance(wfInstance);
268
269            updateList.add(new UpdateEntry<WorkflowActionQuery>(WorkflowActionQuery.UPDATE_ACTION_END,wfAction));
270            wfJob.setLastModifiedTime(new Date());
271            updateList.add(new UpdateEntry<WorkflowJobQuery>(WorkflowJobQuery.UPDATE_WORKFLOW_STATUS_INSTANCE_MODIFIED, wfJob));
272        }
273        finally {
274            try {
275                BatchQueryExecutor.getInstance().executeBatchInsertUpdateDelete(insertList, updateList, null);
276            }
277            catch (JPAExecutorException e) {
278                throw new CommandException(e);
279            }
280            if (!(executor instanceof ControlNodeActionExecutor) && EventHandlerService.isEnabled()) {
281                generateEvent(wfAction, wfJob.getUser());
282            }
283            new SignalXCommand(jobId, actionId).call();
284        }
285
286        LOG.debug("ENDED ActionEndXCommand for action " + actionId);
287        return null;
288    }
289
290}