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.bundle;
020
021import java.io.IOException;
022import java.io.StringReader;
023import java.util.Date;
024import java.util.HashMap;
025import java.util.List;
026import java.util.Map;
027import java.util.Map.Entry;
028
029import org.apache.hadoop.conf.Configuration;
030import org.apache.oozie.BundleActionBean;
031import org.apache.oozie.BundleJobBean;
032import org.apache.oozie.ErrorCode;
033import org.apache.oozie.XException;
034import org.apache.oozie.action.hadoop.OozieJobInfo;
035import org.apache.oozie.client.Job;
036import org.apache.oozie.client.OozieClient;
037import org.apache.oozie.client.rest.JsonBean;
038import org.apache.oozie.command.CommandException;
039import org.apache.oozie.command.PreconditionException;
040import org.apache.oozie.command.StartTransitionXCommand;
041import org.apache.oozie.executor.jpa.BatchQueryExecutor;
042import org.apache.oozie.executor.jpa.BundleJobQueryExecutor;
043import org.apache.oozie.executor.jpa.BundleJobQueryExecutor.BundleJobQuery;
044import org.apache.oozie.executor.jpa.JPAExecutorException;
045import org.apache.oozie.executor.jpa.BatchQueryExecutor.UpdateEntry;
046import org.apache.oozie.util.ConfigUtils;
047import org.apache.oozie.util.ELUtils;
048import org.apache.oozie.util.JobUtils;
049import org.apache.oozie.util.LogUtils;
050import org.apache.oozie.util.ParamChecker;
051import org.apache.oozie.util.XConfiguration;
052import org.apache.oozie.util.XmlUtils;
053import org.jdom.Attribute;
054import org.jdom.Element;
055import org.jdom.JDOMException;
056
057/**
058 * The command to start Bundle job
059 */
060public class BundleStartXCommand extends StartTransitionXCommand {
061    private final String jobId;
062    private BundleJobBean bundleJob;
063
064    /**
065     * The constructor for class {@link BundleStartXCommand}
066     *
067     * @param jobId the bundle job id
068     */
069    public BundleStartXCommand(String jobId) {
070        super("bundle_start", "bundle_start", 1);
071        this.jobId = ParamChecker.notEmpty(jobId, "jobId");
072    }
073
074    /**
075     * The constructor for class {@link BundleStartXCommand}
076     *
077     * @param jobId the bundle job id
078     * @param dryrun true if dryrun is enable
079     */
080    public BundleStartXCommand(String jobId, boolean dryrun) {
081        super("bundle_start", "bundle_start", 1, dryrun);
082        this.jobId = ParamChecker.notEmpty(jobId, "jobId");
083    }
084
085    /* (non-Javadoc)
086     * @see org.apache.oozie.command.XCommand#getEntityKey()
087     */
088    @Override
089    public String getEntityKey() {
090        return jobId;
091    }
092
093    @Override
094    public String getKey() {
095        return getName() + "_" + jobId;
096    }
097
098    /* (non-Javadoc)
099     * @see org.apache.oozie.command.XCommand#isLockRequired()
100     */
101    @Override
102    protected boolean isLockRequired() {
103        return true;
104    }
105
106    @Override
107    protected void verifyPrecondition() throws CommandException, PreconditionException {
108        if (bundleJob.getStatus() != Job.Status.PREP) {
109            String msg = "Bundle " + bundleJob.getId() + " is not in PREP status. It is in : " + bundleJob.getStatus();
110            LOG.info(msg);
111            throw new PreconditionException(ErrorCode.E1100, msg);
112        }
113    }
114
115    @Override
116    public void loadState() throws CommandException {
117        try {
118            this.bundleJob = BundleJobQueryExecutor.getInstance().get(BundleJobQuery.GET_BUNDLE_JOB, jobId);
119            LogUtils.setLogInfo(bundleJob);
120            super.setJob(bundleJob);
121        }
122        catch (XException ex) {
123            throw new CommandException(ex);
124        }
125    }
126
127    /* (non-Javadoc)
128     * @see org.apache.oozie.command.StartTransitionXCommand#StartChildren()
129     */
130    @Override
131    public void StartChildren() throws CommandException {
132        LOG.debug("Started coord jobs for the bundle=[{0}]", jobId);
133        insertBundleActions();
134        startCoordJobs();
135        LOG.debug("Ended coord jobs for the bundle=[{0}]", jobId);
136    }
137
138    /* (non-Javadoc)
139     * @see org.apache.oozie.command.TransitionXCommand#notifyParent()
140     */
141    @Override
142    public void notifyParent() {
143    }
144
145    /* (non-Javadoc)
146     * @see org.apache.oozie.command.StartTransitionXCommand#performWrites()
147     */
148    @Override
149    public void performWrites() throws CommandException {
150        try {
151            BatchQueryExecutor.getInstance().executeBatchInsertUpdateDelete(insertList, updateList, null);
152        }
153        catch (JPAExecutorException e) {
154            throw new CommandException(e);
155        }
156    }
157
158    /**
159     * Insert bundle actions
160     *
161     * @throws CommandException thrown if failed to create bundle actions
162     */
163    @SuppressWarnings("unchecked")
164    private void insertBundleActions() throws CommandException {
165        if (bundleJob != null) {
166            Map<String, Boolean> map = new HashMap<String, Boolean>();
167            try {
168                Element bAppXml = XmlUtils.parseXml(bundleJob.getJobXml());
169                List<Element> coordElems = bAppXml.getChildren("coordinator", bAppXml.getNamespace());
170                for (Element elem : coordElems) {
171                    Attribute name = elem.getAttribute("name");
172                    Attribute critical = elem.getAttribute("critical");
173                    if (name != null) {
174                        if (map.containsKey(name.getValue())) {
175                            throw new CommandException(ErrorCode.E1304, name);
176                        }
177                        Configuration coordConf = mergeConfig(elem);
178                        // skip coord job if it is not enabled
179                        if (!isEnabled(elem, coordConf)) {
180                            continue;
181                        }
182                        boolean isCritical = false;
183                        if (critical != null && Boolean.parseBoolean(critical.getValue())) {
184                            isCritical = true;
185                        }
186                        map.put(name.getValue(), isCritical);
187                    }
188                    else {
189                        throw new CommandException(ErrorCode.E1305);
190                    }
191                }
192            }
193            catch (JDOMException jex) {
194                throw new CommandException(ErrorCode.E1301, jex.getMessage(), jex);
195            }
196
197            // if there is no coordinator for this bundle, failed it.
198            if (map.isEmpty()) {
199                bundleJob.setStatus(Job.Status.FAILED);
200                bundleJob.resetPending();
201                try {
202                    BundleJobQueryExecutor.getInstance().executeUpdate(BundleJobQuery.UPDATE_BUNDLE_JOB_STATUS_PENDING, bundleJob);
203                }
204                catch (JPAExecutorException jex) {
205                    throw new CommandException(jex);
206                }
207
208                LOG.debug("No coord jobs for the bundle=[{0}], failed it!!", jobId);
209                throw new CommandException(ErrorCode.E1318, jobId);
210            }
211
212            for (Entry<String, Boolean> coordName : map.entrySet()) {
213                BundleActionBean action = createBundleAction(jobId, coordName.getKey(), coordName.getValue());
214                insertList.add(action);
215            }
216        }
217        else {
218            throw new CommandException(ErrorCode.E0604, jobId);
219        }
220    }
221
222    private BundleActionBean createBundleAction(String jobId, String coordName, boolean isCritical) {
223        BundleActionBean action = new BundleActionBean();
224        action.setBundleActionId(jobId + "_" + coordName);
225        action.setBundleId(jobId);
226        action.setCoordName(coordName);
227        action.setStatus(Job.Status.PREP);
228        action.setLastModifiedTime(new Date());
229        if (isCritical) {
230            action.setCritical();
231        }
232        else {
233            action.resetCritical();
234        }
235        return action;
236    }
237
238    /**
239     * Start Coord Jobs
240     *
241     * @throws CommandException thrown if failed to start coord jobs
242     */
243    @SuppressWarnings("unchecked")
244    private void startCoordJobs() throws CommandException {
245        if (bundleJob != null) {
246            try {
247                Element bAppXml = XmlUtils.parseXml(bundleJob.getJobXml());
248                List<Element> coordElems = bAppXml.getChildren("coordinator", bAppXml.getNamespace());
249                for (Element coordElem : coordElems) {
250                    Attribute name = coordElem.getAttribute("name");
251
252                    Configuration coordConf = mergeConfig(coordElem);
253                    coordConf.set(OozieClient.BUNDLE_ID, jobId);
254                    if (OozieJobInfo.isJobInfoEnabled()) {
255                        coordConf.set(OozieJobInfo.BUNDLE_NAME, bundleJob.getAppName());
256                    }
257                    // skip coord job if it is not enabled
258                    if (!isEnabled(coordElem, coordConf)) {
259                        continue;
260                    }
261                    String coordName=name.getValue();
262                    try {
263                        coordName = ELUtils.resolveAppName(coordName, coordConf);
264                    }
265                    catch (Exception e) {
266                        throw new CommandException(ErrorCode.E1321, e.getMessage(), e);
267
268                    }
269                    queue(new BundleCoordSubmitXCommand(coordConf, bundleJob.getId(), name.getValue()));
270
271                }
272                updateBundleAction();
273            }
274            catch (JDOMException jex) {
275                throw new CommandException(ErrorCode.E1301, jex.getMessage(), jex);
276            }
277            catch (JPAExecutorException je) {
278                throw new CommandException(je);
279            }
280        }
281        else {
282            throw new CommandException(ErrorCode.E0604, jobId);
283        }
284    }
285
286    private void updateBundleAction() throws JPAExecutorException {
287        for(JsonBean bAction : insertList) {
288            BundleActionBean action = (BundleActionBean) bAction;
289            action.incrementAndGetPending();
290            action.setLastModifiedTime(new Date());
291        }
292    }
293
294    /**
295     * Merge Bundle job config and the configuration from the coord job to pass
296     * to Coord Engine
297     *
298     * @param coordElem the coordinator configuration
299     * @return Configuration merged configuration
300     * @throws CommandException thrown if failed to merge configuration
301     */
302    private Configuration mergeConfig(Element coordElem) throws CommandException {
303        String jobConf = bundleJob.getConf();
304        // Step 1: runConf = jobConf
305        Configuration runConf = null;
306        try {
307            runConf = new XConfiguration(new StringReader(jobConf));
308        }
309        catch (IOException e1) {
310            LOG.warn("Configuration parse error in:" + jobConf);
311            throw new CommandException(ErrorCode.E1306, e1.getMessage(), e1);
312        }
313        // Step 2: Merge local properties into runConf
314        // extract 'property' tags under 'configuration' block in the coordElem
315        // convert Element to XConfiguration
316        Element localConfigElement = coordElem.getChild("configuration", coordElem.getNamespace());
317
318        if (localConfigElement != null) {
319            String strConfig = XmlUtils.prettyPrint(localConfigElement).toString();
320            Configuration localConf;
321            try {
322                localConf = new XConfiguration(new StringReader(strConfig));
323            }
324            catch (IOException e1) {
325                LOG.warn("Configuration parse error in:" + strConfig);
326                throw new CommandException(ErrorCode.E1307, e1.getMessage(), e1);
327            }
328
329            // copy configuration properties in the coordElem to the runConf
330            XConfiguration.copy(localConf, runConf);
331
332            ConfigUtils.checkAndSetDisallowedProperties(runConf,
333                    bundleJob.getUser(),
334                    new CommandException(ErrorCode.E1303,
335                            String.format("%s=%s", OozieClient.USER_NAME, runConf.get(OozieClient.USER_NAME)),
336                            bundleJob.getUser()),
337                    true);
338        }
339
340        // Step 3: Extract value of 'app-path' in coordElem, save it as a
341        // new property called 'oozie.coord.application.path', and normalize.
342        String appPath = coordElem.getChild("app-path", coordElem.getNamespace()).getValue();
343        runConf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
344        // Normalize coordinator appPath here;
345        try {
346            JobUtils.normalizeAppPath(runConf.get(OozieClient.USER_NAME), runConf.get(OozieClient.GROUP_NAME), runConf);
347        }
348        catch (IOException e) {
349            throw new CommandException(ErrorCode.E1001, runConf.get(OozieClient.COORDINATOR_APP_PATH));
350        }
351        return runConf;
352    }
353
354    /* (non-Javadoc)
355     * @see org.apache.oozie.command.TransitionXCommand#getJob()
356     */
357    @Override
358    public Job getJob() {
359        return bundleJob;
360    }
361
362    /* (non-Javadoc)
363     * @see org.apache.oozie.command.TransitionXCommand#updateJob()
364     */
365    @Override
366    public void updateJob() throws CommandException {
367        updateList.add(new UpdateEntry<BundleJobQuery>(BundleJobQuery.UPDATE_BUNDLE_JOB_STATUS_PENDING, bundleJob));
368    }
369
370    /**
371     * Checks whether the coordinator is enabled
372     *
373     * @param coordElem
374     * @param coordConf
375     * @return true if coordinator is enabled, otherwise false.
376     * @throws CommandException
377     */
378    private boolean isEnabled(Element coordElem, Configuration coordConf) throws CommandException {
379        Attribute enabled = coordElem.getAttribute("enabled");
380        if (enabled == null) {
381            // default is true
382            return true;
383        }
384        String isEnabled = enabled.getValue();
385        try {
386            isEnabled = ELUtils.resolveAppName(isEnabled, coordConf);
387        }
388        catch (Exception e) {
389            throw new CommandException(ErrorCode.E1321, e.getMessage(), e);
390        }
391        return Boolean.parseBoolean(isEnabled);
392    }
393
394}