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 java.io.IOException; 022import java.io.InputStreamReader; 023import java.io.Reader; 024import java.io.StringReader; 025import java.io.StringWriter; 026import java.net.URI; 027import java.net.URISyntaxException; 028import java.util.ArrayList; 029import java.util.Calendar; 030import java.util.Date; 031import java.util.HashMap; 032import java.util.HashSet; 033import java.util.Iterator; 034import java.util.List; 035import java.util.Map; 036import java.util.Set; 037import java.util.TreeSet; 038 039import javax.xml.transform.stream.StreamSource; 040import javax.xml.validation.Validator; 041 042import org.apache.hadoop.conf.Configuration; 043import org.apache.hadoop.fs.FileSystem; 044import org.apache.hadoop.fs.Path; 045import org.apache.oozie.CoordinatorJobBean; 046import org.apache.oozie.ErrorCode; 047import org.apache.oozie.client.CoordinatorJob; 048import org.apache.oozie.client.Job; 049import org.apache.oozie.client.OozieClient; 050import org.apache.oozie.client.CoordinatorJob.Execution; 051import org.apache.oozie.command.CommandException; 052import org.apache.oozie.command.SubmitTransitionXCommand; 053import org.apache.oozie.command.bundle.BundleStatusUpdateXCommand; 054import org.apache.oozie.coord.CoordELEvaluator; 055import org.apache.oozie.coord.CoordELFunctions; 056import org.apache.oozie.coord.CoordUtils; 057import org.apache.oozie.coord.CoordinatorJobException; 058import org.apache.oozie.coord.TimeUnit; 059import org.apache.oozie.coord.input.logic.CoordInputLogicEvaluator; 060import org.apache.oozie.executor.jpa.CoordJobQueryExecutor; 061import org.apache.oozie.executor.jpa.JPAExecutorException; 062import org.apache.oozie.service.CoordMaterializeTriggerService; 063import org.apache.oozie.service.ConfigurationService; 064import org.apache.oozie.service.HadoopAccessorException; 065import org.apache.oozie.service.HadoopAccessorService; 066import org.apache.oozie.service.JPAService; 067import org.apache.oozie.service.SchemaService; 068import org.apache.oozie.service.Service; 069import org.apache.oozie.service.Services; 070import org.apache.oozie.service.UUIDService; 071import org.apache.oozie.service.SchemaService.SchemaName; 072import org.apache.oozie.service.UUIDService.ApplicationType; 073import org.apache.oozie.util.ConfigUtils; 074import org.apache.oozie.util.DateUtils; 075import org.apache.oozie.util.ELEvaluator; 076import org.apache.oozie.util.ELUtils; 077import org.apache.oozie.util.IOUtils; 078import org.apache.oozie.util.InstrumentUtils; 079import org.apache.oozie.util.LogUtils; 080import org.apache.oozie.util.ParamChecker; 081import org.apache.oozie.util.ParameterVerifier; 082import org.apache.oozie.util.ParameterVerifierException; 083import org.apache.oozie.util.PropertiesUtils; 084import org.apache.oozie.util.XConfiguration; 085import org.apache.oozie.util.XmlUtils; 086import org.jdom.Attribute; 087import org.jdom.Element; 088import org.jdom.JDOMException; 089import org.jdom.Namespace; 090import org.xml.sax.SAXException; 091 092/** 093 * This class provides the functionalities to resolve a coordinator job XML and write the job information into a DB 094 * table. 095 * <p> 096 * Specifically it performs the following functions: 1. Resolve all the variables or properties using job 097 * configurations. 2. Insert all datasets definition as part of the <data-in> and <data-out> tags. 3. Validate the XML 098 * at runtime. 099 */ 100public class CoordSubmitXCommand extends SubmitTransitionXCommand { 101 102 protected Configuration conf; 103 protected final String bundleId; 104 protected final String coordName; 105 protected boolean dryrun; 106 protected JPAService jpaService = null; 107 private CoordinatorJob.Status prevStatus = CoordinatorJob.Status.PREP; 108 109 public static final String CONFIG_DEFAULT = "coord-config-default.xml"; 110 public static final String COORDINATOR_XML_FILE = "coordinator.xml"; 111 public final String COORD_INPUT_EVENTS ="input-events"; 112 public final String COORD_OUTPUT_EVENTS = "output-events"; 113 public final String COORD_INPUT_EVENTS_DATA_IN ="data-in"; 114 public final String COORD_OUTPUT_EVENTS_DATA_OUT = "data-out"; 115 116 private static final Set<String> DISALLOWED_USER_PROPERTIES = new HashSet<String>(); 117 private static final Set<String> DISALLOWED_DEFAULT_PROPERTIES = new HashSet<String>(); 118 119 protected CoordinatorJobBean coordJob = null; 120 /** 121 * Default timeout for normal jobs, in minutes, after which coordinator input check will timeout 122 */ 123 public static final String CONF_DEFAULT_TIMEOUT_NORMAL = Service.CONF_PREFIX + "coord.normal.default.timeout"; 124 125 public static final String CONF_DEFAULT_CONCURRENCY = Service.CONF_PREFIX + "coord.default.concurrency"; 126 127 public static final String CONF_DEFAULT_THROTTLE = Service.CONF_PREFIX + "coord.default.throttle"; 128 129 public static final String CONF_MAT_THROTTLING_FACTOR = Service.CONF_PREFIX 130 + "coord.materialization.throttling.factor"; 131 132 /** 133 * Default MAX timeout in minutes, after which coordinator input check will timeout 134 */ 135 public static final String CONF_DEFAULT_MAX_TIMEOUT = Service.CONF_PREFIX + "coord.default.max.timeout"; 136 137 public static final String CONF_QUEUE_SIZE = Service.CONF_PREFIX + "CallableQueueService.queue.size"; 138 139 public static final String CONF_CHECK_MAX_FREQUENCY = Service.CONF_PREFIX + "coord.check.maximum.frequency"; 140 141 private ELEvaluator evalFreq = null; 142 private ELEvaluator evalNofuncs = null; 143 private ELEvaluator evalData = null; 144 private ELEvaluator evalInst = null; 145 private ELEvaluator evalAction = null; 146 private ELEvaluator evalSla = null; 147 private ELEvaluator evalTimeout = null; 148 private ELEvaluator evalInitialInstance = null; 149 150 static { 151 String[] badUserProps = { PropertiesUtils.YEAR, PropertiesUtils.MONTH, PropertiesUtils.DAY, 152 PropertiesUtils.HOUR, PropertiesUtils.MINUTE, PropertiesUtils.DAYS, PropertiesUtils.HOURS, 153 PropertiesUtils.MINUTES, PropertiesUtils.KB, PropertiesUtils.MB, PropertiesUtils.GB, 154 PropertiesUtils.TB, PropertiesUtils.PB, PropertiesUtils.RECORDS, PropertiesUtils.MAP_IN, 155 PropertiesUtils.MAP_OUT, PropertiesUtils.REDUCE_IN, PropertiesUtils.REDUCE_OUT, PropertiesUtils.GROUPS }; 156 PropertiesUtils.createPropertySet(badUserProps, DISALLOWED_USER_PROPERTIES); 157 } 158 159 /** 160 * Constructor to create the Coordinator Submit Command. 161 * 162 * @param conf : Configuration for Coordinator job 163 */ 164 public CoordSubmitXCommand(Configuration conf) { 165 super("coord_submit", "coord_submit", 1); 166 this.conf = ParamChecker.notNull(conf, "conf"); 167 this.bundleId = null; 168 this.coordName = null; 169 } 170 171 /** 172 * Constructor to create the Coordinator Submit Command by bundle job. 173 * 174 * @param conf : Configuration for Coordinator job 175 * @param bundleId : bundle id 176 * @param coordName : coord name 177 */ 178 protected CoordSubmitXCommand(Configuration conf, String bundleId, String coordName) { 179 super("coord_submit", "coord_submit", 1); 180 this.conf = ParamChecker.notNull(conf, "conf"); 181 this.bundleId = ParamChecker.notEmpty(bundleId, "bundleId"); 182 this.coordName = ParamChecker.notEmpty(coordName, "coordName"); 183 } 184 185 /** 186 * Constructor to create the Coordinator Submit Command. 187 * 188 * @param dryrun : if dryrun 189 * @param conf : Configuration for Coordinator job 190 */ 191 public CoordSubmitXCommand(boolean dryrun, Configuration conf) { 192 this(conf); 193 this.dryrun = dryrun; 194 } 195 196 /* (non-Javadoc) 197 * @see org.apache.oozie.command.XCommand#execute() 198 */ 199 @Override 200 protected String submit() throws CommandException { 201 LOG.info("STARTED Coordinator Submit"); 202 String jobId = submitJob(); 203 LOG.info("ENDED Coordinator Submit jobId=" + jobId); 204 return jobId; 205 } 206 207 protected String submitJob() throws CommandException { 208 String jobId = null; 209 InstrumentUtils.incrJobCounter(getName(), 1, getInstrumentation()); 210 211 boolean exceptionOccured = false; 212 try { 213 mergeDefaultConfig(); 214 215 String appXml = readAndValidateXml(); 216 coordJob.setOrigJobXml(appXml); 217 LOG.debug("jobXml after initial validation " + XmlUtils.prettyPrint(appXml).toString()); 218 219 Element eXml = XmlUtils.parseXml(appXml); 220 221 String appNamespace = readAppNamespace(eXml); 222 coordJob.setAppNamespace(appNamespace); 223 224 ParameterVerifier.verifyParameters(conf, eXml); 225 226 appXml = XmlUtils.removeComments(appXml); 227 initEvaluators(); 228 Element eJob = basicResolveAndIncludeDS(appXml, conf, coordJob); 229 230 validateCoordinatorJob(); 231 232 // checking if the coordinator application data input/output events 233 // specify multiple data instance values in erroneous manner 234 checkMultipleTimeInstances(eJob, COORD_INPUT_EVENTS, COORD_INPUT_EVENTS_DATA_IN); 235 checkMultipleTimeInstances(eJob, COORD_OUTPUT_EVENTS, COORD_OUTPUT_EVENTS_DATA_OUT); 236 237 LOG.debug("jobXml after all validation " + XmlUtils.prettyPrint(eJob).toString()); 238 239 jobId = storeToDB(appXml, eJob, coordJob); 240 // log job info for coordinator job 241 LogUtils.setLogInfo(coordJob); 242 243 if (!dryrun) { 244 queueMaterializeTransitionXCommand(jobId); 245 } 246 else { 247 return getDryRun(coordJob); 248 } 249 } 250 catch (JDOMException jex) { 251 exceptionOccured = true; 252 LOG.warn("ERROR: ", jex); 253 throw new CommandException(ErrorCode.E0700, jex.getMessage(), jex); 254 } 255 catch (CoordinatorJobException cex) { 256 exceptionOccured = true; 257 LOG.warn("ERROR: ", cex); 258 throw new CommandException(cex); 259 } 260 catch (ParameterVerifierException pex) { 261 exceptionOccured = true; 262 LOG.warn("ERROR: ", pex); 263 throw new CommandException(pex); 264 } 265 catch (IllegalArgumentException iex) { 266 exceptionOccured = true; 267 LOG.warn("ERROR: ", iex); 268 throw new CommandException(ErrorCode.E1003, iex.getMessage(), iex); 269 } 270 catch (Exception ex) { 271 exceptionOccured = true; 272 LOG.warn("ERROR: ", ex); 273 throw new CommandException(ErrorCode.E0803, ex.getMessage(), ex); 274 } 275 finally { 276 if (exceptionOccured) { 277 if (coordJob.getId() == null || coordJob.getId().equalsIgnoreCase("")) { 278 coordJob.setStatus(CoordinatorJob.Status.FAILED); 279 coordJob.resetPending(); 280 } 281 } 282 } 283 return jobId; 284 } 285 286 /** 287 * Gets the dryrun output. 288 * 289 * @param coordJob the coordinatorJobBean 290 * @return the dry run 291 * @throws Exception the exception 292 */ 293 protected String getDryRun(CoordinatorJobBean coordJob) throws Exception{ 294 int materializationWindow = ConfigurationService 295 .getInt(CoordMaterializeTriggerService.CONF_MATERIALIZATION_WINDOW); 296 Date startTime = coordJob.getStartTime(); 297 long startTimeMilli = startTime.getTime(); 298 long endTimeMilli = startTimeMilli + (materializationWindow * 1000); 299 Date jobEndTime = coordJob.getEndTime(); 300 Date endTime = new Date(endTimeMilli); 301 if (endTime.compareTo(jobEndTime) > 0) { 302 endTime = jobEndTime; 303 } 304 String jobId = coordJob.getId(); 305 LOG.info("[" + jobId + "]: Update status to RUNNING"); 306 coordJob.setStatus(Job.Status.RUNNING); 307 coordJob.setPending(); 308 Configuration jobConf = null; 309 try { 310 jobConf = new XConfiguration(new StringReader(coordJob.getConf())); 311 } 312 catch (IOException e1) { 313 LOG.warn("Configuration parse error. read from DB :" + coordJob.getConf(), e1); 314 } 315 String action = new CoordMaterializeTransitionXCommand(coordJob, materializationWindow, startTime, 316 endTime).materializeActions(true); 317 String output = coordJob.getJobXml() + System.getProperty("line.separator") 318 + "***actions for instance***" + action; 319 return output; 320 } 321 322 /** 323 * Queue MaterializeTransitionXCommand 324 */ 325 protected void queueMaterializeTransitionXCommand(String jobId) { 326 int materializationWindow = ConfigurationService 327 .getInt(CoordMaterializeTriggerService.CONF_MATERIALIZATION_WINDOW); 328 queue(new CoordMaterializeTransitionXCommand(jobId, materializationWindow), 100); 329 } 330 331 /** 332 * Method that validates values in the definition for correctness. Placeholder to add more. 333 */ 334 private void validateCoordinatorJob() throws Exception { 335 // check if startTime < endTime 336 if (!coordJob.getStartTime().before(coordJob.getEndTime())) { 337 throw new IllegalArgumentException("Coordinator Start Time must be earlier than End Time."); 338 } 339 340 try { 341 // Check if a coord job with cron frequency will materialize actions 342 int freq = Integer.parseInt(coordJob.getFrequency()); 343 344 // Check if the frequency is faster than 5 min if enabled 345 if (ConfigurationService.getBoolean(CONF_CHECK_MAX_FREQUENCY)) { 346 CoordinatorJob.Timeunit unit = coordJob.getTimeUnit(); 347 if (freq == 0 || (freq < 5 && unit == CoordinatorJob.Timeunit.MINUTE)) { 348 throw new IllegalArgumentException("Coordinator job with frequency [" + freq + 349 "] minutes is faster than allowed maximum of 5 minutes (" 350 + CONF_CHECK_MAX_FREQUENCY + " is set to true)"); 351 } 352 } 353 } catch (NumberFormatException e) { 354 Date start = coordJob.getStartTime(); 355 Calendar cal = Calendar.getInstance(); 356 cal.setTime(start); 357 cal.add(Calendar.MINUTE, -1); 358 start = cal.getTime(); 359 360 Date nextTime = CoordCommandUtils.getNextValidActionTimeForCronFrequency(start, coordJob); 361 if (nextTime == null) { 362 throw new IllegalArgumentException("Invalid coordinator cron frequency: " + coordJob.getFrequency()); 363 } 364 if (!nextTime.before(coordJob.getEndTime())) { 365 throw new IllegalArgumentException("Coordinator job with frequency '" + 366 coordJob.getFrequency() + "' materializes no actions between start and end time."); 367 } 368 } 369 } 370 371 /* 372 * Check against multiple data instance values inside a single <instance> <start-instance> or <end-instance> tag 373 * If found, the job is not submitted and user is informed to correct the error, 374 * instead of defaulting to the first instance value in the list 375 */ 376 private void checkMultipleTimeInstances(Element eCoordJob, String eventType, String dataType) throws CoordinatorJobException { 377 Element eventsSpec, dataSpec, instance; 378 List<Element> instanceSpecList; 379 Namespace ns = eCoordJob.getNamespace(); 380 String instanceValue; 381 eventsSpec = eCoordJob.getChild(eventType, ns); 382 if (eventsSpec != null) { 383 dataSpec = eventsSpec.getChild(dataType, ns); 384 if (dataSpec != null) { 385 // In case of input-events, there can be multiple child <instance> datasets. 386 // Iterating to ensure none of them have errors 387 instanceSpecList = dataSpec.getChildren("instance", ns); 388 Iterator instanceIter = instanceSpecList.iterator(); 389 while(instanceIter.hasNext()) { 390 instance = ((Element) instanceIter.next()); 391 if(instance.getContentSize() == 0) { //empty string or whitespace 392 throw new CoordinatorJobException(ErrorCode.E1021, "<instance> tag within " + eventType + " is empty!"); 393 } 394 instanceValue = instance.getContent(0).toString(); 395 boolean isInvalid = false; 396 try { 397 isInvalid = evalAction.checkForExistence(instanceValue, ","); 398 } catch (Exception e) { 399 handleELParseException(eventType, dataType, instanceValue); 400 } 401 if (isInvalid) { // reaching this block implies instance is not empty i.e. length > 0 402 handleExpresionWithMultipleInstances(eventType, dataType, instanceValue); 403 } 404 } 405 406 // In case of input-events, there can be multiple child <start-instance> datasets. 407 // Iterating to ensure none of them have errors 408 instanceSpecList = dataSpec.getChildren("start-instance", ns); 409 instanceIter = instanceSpecList.iterator(); 410 while(instanceIter.hasNext()) { 411 instance = ((Element) instanceIter.next()); 412 if(instance.getContentSize() == 0) { //empty string or whitespace 413 throw new CoordinatorJobException(ErrorCode.E1021, "<start-instance> tag within " + eventType 414 + " is empty!"); 415 } 416 instanceValue = instance.getContent(0).toString(); 417 boolean isInvalid = false; 418 try { 419 isInvalid = evalAction.checkForExistence(instanceValue, ","); 420 } catch (Exception e) { 421 handleELParseException(eventType, dataType, instanceValue); 422 } 423 if (isInvalid) { // reaching this block implies start instance is not empty i.e. length > 0 424 handleExpresionWithStartMultipleInstances(eventType, dataType, instanceValue); 425 } 426 } 427 428 // In case of input-events, there can be multiple child <end-instance> datasets. 429 // Iterating to ensure none of them have errors 430 instanceSpecList = dataSpec.getChildren("end-instance", ns); 431 instanceIter = instanceSpecList.iterator(); 432 while(instanceIter.hasNext()) { 433 instance = ((Element) instanceIter.next()); 434 if(instance.getContentSize() == 0) { //empty string or whitespace 435 throw new CoordinatorJobException(ErrorCode.E1021, "<end-instance> tag within " + eventType + " is empty!"); 436 } 437 instanceValue = instance.getContent(0).toString(); 438 boolean isInvalid = false; 439 try { 440 isInvalid = evalAction.checkForExistence(instanceValue, ","); 441 } catch (Exception e) { 442 handleELParseException(eventType, dataType, instanceValue); 443 } 444 if (isInvalid) { // reaching this block implies instance is not empty i.e. length > 0 445 handleExpresionWithMultipleEndInstances(eventType, dataType, instanceValue); 446 } 447 } 448 449 } 450 } 451 } 452 453 private void handleELParseException(String eventType, String dataType, String instanceValue) 454 throws CoordinatorJobException { 455 String correctAction = null; 456 if(dataType.equals(COORD_INPUT_EVENTS_DATA_IN)) { 457 correctAction = "Coordinator app definition should have valid <instance> tag for data-in"; 458 } else if(dataType.equals(COORD_OUTPUT_EVENTS_DATA_OUT)) { 459 correctAction = "Coordinator app definition should have valid <instance> tag for data-out"; 460 } 461 throw new CoordinatorJobException(ErrorCode.E1021, eventType + " instance '" + instanceValue 462 + "' is not valid. Coordinator job NOT SUBMITTED. " + correctAction); 463 } 464 465 private void handleExpresionWithMultipleInstances(String eventType, String dataType, String instanceValue) 466 throws CoordinatorJobException { 467 String correctAction = null; 468 if(dataType.equals(COORD_INPUT_EVENTS_DATA_IN)) { 469 correctAction = "Coordinator app definition should have separate <instance> tag per data-in instance"; 470 } else if(dataType.equals(COORD_OUTPUT_EVENTS_DATA_OUT)) { 471 correctAction = "Coordinator app definition can have only one <instance> tag per data-out instance"; 472 } 473 throw new CoordinatorJobException(ErrorCode.E1021, eventType + " instance '" + instanceValue 474 + "' contains more than one date instance. Coordinator job NOT SUBMITTED. " + correctAction); 475 } 476 477 private void handleExpresionWithStartMultipleInstances(String eventType, String dataType, String instanceValue) 478 throws CoordinatorJobException { 479 String correctAction = "Coordinator app definition should not have multiple start-instances"; 480 throw new CoordinatorJobException(ErrorCode.E1021, eventType + " start-instance '" + instanceValue 481 + "' contains more than one date start-instance. Coordinator job NOT SUBMITTED. " + correctAction); 482 } 483 484 private void handleExpresionWithMultipleEndInstances(String eventType, String dataType, String instanceValue) 485 throws CoordinatorJobException { 486 String correctAction = "Coordinator app definition should not have multiple end-instances"; 487 throw new CoordinatorJobException(ErrorCode.E1021, eventType + " end-instance '" + instanceValue 488 + "' contains more than one date end-instance. Coordinator job NOT SUBMITTED. " + correctAction); 489 } 490 /** 491 * Read the application XML and validate against coordinator Schema 492 * 493 * @return validated coordinator XML 494 * @throws CoordinatorJobException thrown if unable to read or validate coordinator xml 495 */ 496 protected String readAndValidateXml() throws CoordinatorJobException { 497 String appPath = ParamChecker.notEmpty(conf.get(OozieClient.COORDINATOR_APP_PATH), 498 OozieClient.COORDINATOR_APP_PATH); 499 String coordXml = readDefinition(appPath); 500 validateXml(coordXml); 501 return coordXml; 502 } 503 504 /** 505 * Validate against Coordinator XSD file 506 * 507 * @param xmlContent : Input coordinator xml 508 * @throws CoordinatorJobException thrown if unable to validate coordinator xml 509 */ 510 private void validateXml(String xmlContent) throws CoordinatorJobException { 511 try { 512 Validator validator = Services.get().get(SchemaService.class).getValidator(SchemaName.COORDINATOR); 513 validator.validate(new StreamSource(new StringReader(xmlContent))); 514 } 515 catch (SAXException ex) { 516 LOG.warn("SAXException :", ex); 517 throw new CoordinatorJobException(ErrorCode.E0701, ex.getMessage(), ex); 518 } 519 catch (IOException ex) { 520 LOG.warn("IOException :", ex); 521 throw new CoordinatorJobException(ErrorCode.E0702, ex.getMessage(), ex); 522 } 523 } 524 525 /** 526 * Read the application XML schema namespace 527 * 528 * @param coordXmlElement input coordinator xml Element 529 * @return app xml namespace 530 * @throws CoordinatorJobException 531 */ 532 private String readAppNamespace(Element coordXmlElement) throws CoordinatorJobException { 533 Namespace ns = coordXmlElement.getNamespace(); 534 if (ns != null && bundleId != null && ns.getURI().equals(SchemaService.COORDINATOR_NAMESPACE_URI_1)) { 535 throw new CoordinatorJobException(ErrorCode.E1319, "bundle app can not submit coordinator namespace " 536 + SchemaService.COORDINATOR_NAMESPACE_URI_1 + ", please use 0.2 or later"); 537 } 538 if (ns != null) { 539 return ns.getURI(); 540 } 541 else { 542 throw new CoordinatorJobException(ErrorCode.E0700, "the application xml namespace is not given"); 543 } 544 } 545 546 /** 547 * Merge default configuration with user-defined configuration. 548 * 549 * @throws CommandException thrown if failed to read or merge configurations 550 */ 551 protected void mergeDefaultConfig() throws CommandException { 552 Path configDefault = null; 553 try { 554 String coordAppPathStr = conf.get(OozieClient.COORDINATOR_APP_PATH); 555 Path coordAppPath = new Path(coordAppPathStr); 556 String user = ParamChecker.notEmpty(conf.get(OozieClient.USER_NAME), OozieClient.USER_NAME); 557 HadoopAccessorService has = Services.get().get(HadoopAccessorService.class); 558 Configuration fsConf = has.createConfiguration(coordAppPath.toUri().getAuthority()); 559 FileSystem fs = has.createFileSystem(user, coordAppPath.toUri(), fsConf); 560 561 // app path could be a directory 562 if (!fs.isFile(coordAppPath)) { 563 configDefault = new Path(coordAppPath, CONFIG_DEFAULT); 564 } else { 565 configDefault = new Path(coordAppPath.getParent(), CONFIG_DEFAULT); 566 } 567 568 if (fs.exists(configDefault)) { 569 Configuration defaultConf = new XConfiguration(fs.open(configDefault)); 570 PropertiesUtils.checkDisallowedProperties(defaultConf, DISALLOWED_USER_PROPERTIES); 571 PropertiesUtils.checkDefaultDisallowedProperties(defaultConf); 572 XConfiguration.injectDefaults(defaultConf, conf); 573 } 574 else { 575 LOG.info("configDefault Doesn't exist " + configDefault); 576 } 577 PropertiesUtils.checkDisallowedProperties(conf, DISALLOWED_USER_PROPERTIES); 578 579 // Resolving all variables in the job properties. 580 // This ensures the Hadoop Configuration semantics is preserved. 581 XConfiguration resolvedVarsConf = new XConfiguration(); 582 for (Map.Entry<String, String> entry : conf) { 583 resolvedVarsConf.set(entry.getKey(), conf.get(entry.getKey())); 584 } 585 conf = resolvedVarsConf; 586 } 587 catch (IOException e) { 588 throw new CommandException(ErrorCode.E0702, e.getMessage() + " : Problem reading default config " 589 + configDefault, e); 590 } 591 catch (HadoopAccessorException e) { 592 throw new CommandException(e); 593 } 594 LOG.debug("Merged CONF :" + XmlUtils.prettyPrint(conf).toString()); 595 } 596 597 /** 598 * The method resolve all the variables that are defined in configuration. It also include the data set definition 599 * from dataset file into XML. 600 * 601 * @param appXml : Original job XML 602 * @param conf : Configuration of the job 603 * @param coordJob : Coordinator job bean to be populated. 604 * @return Resolved and modified job XML element. 605 * @throws CoordinatorJobException thrown if failed to resolve basic entities or include referred datasets 606 * @throws Exception thrown if failed to resolve basic entities or include referred datasets 607 */ 608 public Element basicResolveAndIncludeDS(String appXml, Configuration conf, CoordinatorJobBean coordJob) 609 throws CoordinatorJobException, Exception { 610 Element basicResolvedApp = resolveInitial(conf, appXml, coordJob); 611 includeDataSets(basicResolvedApp, conf); 612 return basicResolvedApp; 613 } 614 615 /** 616 * Insert data set into data-in and data-out tags. 617 * 618 * @param eAppXml : coordinator application XML 619 * @param eDatasets : DataSet XML 620 */ 621 @SuppressWarnings("unchecked") 622 private void insertDataSet(Element eAppXml, Element eDatasets) { 623 // Adding DS definition in the coordinator XML 624 Element inputList = eAppXml.getChild("input-events", eAppXml.getNamespace()); 625 if (inputList != null) { 626 for (Element dataIn : (List<Element>) inputList.getChildren("data-in", eAppXml.getNamespace())) { 627 Element eDataset = findDataSet(eDatasets, dataIn.getAttributeValue("dataset")); 628 dataIn.getContent().add(0, eDataset); 629 } 630 } 631 Element outputList = eAppXml.getChild("output-events", eAppXml.getNamespace()); 632 if (outputList != null) { 633 for (Element dataOut : (List<Element>) outputList.getChildren("data-out", eAppXml.getNamespace())) { 634 Element eDataset = findDataSet(eDatasets, dataOut.getAttributeValue("dataset")); 635 dataOut.getContent().add(0, eDataset); 636 } 637 } 638 } 639 640 /** 641 * Find a specific dataset from a list of Datasets. 642 * 643 * @param eDatasets : List of data sets 644 * @param name : queried data set name 645 * @return one Dataset element. otherwise throw Exception 646 */ 647 @SuppressWarnings("unchecked") 648 private static Element findDataSet(Element eDatasets, String name) { 649 for (Element eDataset : (List<Element>) eDatasets.getChildren("dataset", eDatasets.getNamespace())) { 650 if (eDataset.getAttributeValue("name").equals(name)) { 651 eDataset = (Element) eDataset.clone(); 652 eDataset.detach(); 653 return eDataset; 654 } 655 } 656 throw new RuntimeException("undefined dataset: " + name); 657 } 658 659 /** 660 * Initialize all the required EL Evaluators. 661 */ 662 protected void initEvaluators() { 663 evalFreq = CoordELEvaluator.createELEvaluatorForGroup(conf, "coord-job-submit-freq"); 664 evalNofuncs = CoordELEvaluator.createELEvaluatorForGroup(conf, "coord-job-submit-nofuncs"); 665 evalInst = CoordELEvaluator.createELEvaluatorForGroup(conf, "coord-job-submit-instances"); 666 evalAction = CoordELEvaluator.createELEvaluatorForGroup(conf, "coord-action-start"); 667 evalTimeout = CoordELEvaluator.createELEvaluatorForGroup(conf, "coord-job-wait-timeout"); 668 evalInitialInstance = CoordELEvaluator.createELEvaluatorForGroup(conf, "coord-job-submit-initial-instance"); 669 670 } 671 672 /** 673 * Resolve basic entities using job Configuration. 674 * 675 * @param conf :Job configuration 676 * @param appXml : Original job XML 677 * @param coordJob : Coordinator job bean to be populated. 678 * @return Resolved job XML element. 679 * @throws CoordinatorJobException thrown if failed to resolve basic entities 680 * @throws Exception thrown if failed to resolve basic entities 681 */ 682 @SuppressWarnings("unchecked") 683 protected Element resolveInitial(Configuration conf, String appXml, CoordinatorJobBean coordJob) 684 throws CoordinatorJobException, Exception { 685 Element eAppXml = XmlUtils.parseXml(appXml); 686 // job's main attributes 687 // frequency 688 String val = resolveAttribute("frequency", eAppXml, evalFreq); 689 int ival = 0; 690 691 val = ParamChecker.checkFrequency(val); 692 coordJob.setFrequency(val); 693 TimeUnit tmp = (evalFreq.getVariable("timeunit") == null) ? TimeUnit.MINUTE : ((TimeUnit) evalFreq 694 .getVariable("timeunit")); 695 try { 696 Integer.parseInt(val); 697 } 698 catch (NumberFormatException ex) { 699 tmp=TimeUnit.CRON; 700 } 701 702 addAnAttribute("freq_timeunit", eAppXml, tmp.toString()); 703 // TimeUnit 704 coordJob.setTimeUnit(CoordinatorJob.Timeunit.valueOf(tmp.toString())); 705 // End Of Duration 706 tmp = evalFreq.getVariable("endOfDuration") == null ? TimeUnit.NONE : ((TimeUnit) evalFreq 707 .getVariable("endOfDuration")); 708 addAnAttribute("end_of_duration", eAppXml, tmp.toString()); 709 // coordJob.setEndOfDuration(tmp) // TODO: Add new attribute in Job bean 710 711 // Application name 712 if (this.coordName == null) { 713 String name = ELUtils.resolveAppName(eAppXml.getAttribute("name").getValue(), conf); 714 coordJob.setAppName(name); 715 } 716 else { 717 // this coord job is created from bundle 718 coordJob.setAppName(this.coordName); 719 } 720 721 // start time 722 val = resolveAttribute("start", eAppXml, evalNofuncs); 723 ParamChecker.checkDateOozieTZ(val, "start"); 724 coordJob.setStartTime(DateUtils.parseDateOozieTZ(val)); 725 // end time 726 val = resolveAttribute("end", eAppXml, evalNofuncs); 727 ParamChecker.checkDateOozieTZ(val, "end"); 728 coordJob.setEndTime(DateUtils.parseDateOozieTZ(val)); 729 // Time zone 730 val = resolveAttribute("timezone", eAppXml, evalNofuncs); 731 ParamChecker.checkTimeZone(val, "timezone"); 732 coordJob.setTimeZone(val); 733 734 // controls 735 val = resolveTagContents("timeout", eAppXml.getChild("controls", eAppXml.getNamespace()), evalTimeout); 736 if (val != null && val != "") { 737 int t = Integer.parseInt(val); 738 tmp = (evalTimeout.getVariable("timeunit") == null) ? TimeUnit.MINUTE : ((TimeUnit) evalTimeout 739 .getVariable("timeunit")); 740 switch (tmp) { 741 case HOUR: 742 val = String.valueOf(t * 60); 743 break; 744 case DAY: 745 val = String.valueOf(t * 60 * 24); 746 break; 747 case MONTH: 748 val = String.valueOf(t * 60 * 24 * 30); 749 break; 750 default: 751 break; 752 } 753 } 754 else { 755 val = ConfigurationService.get(CONF_DEFAULT_TIMEOUT_NORMAL); 756 } 757 758 ival = ParamChecker.checkInteger(val, "timeout"); 759 if (ival < 0 || ival > ConfigurationService.getInt(CONF_DEFAULT_MAX_TIMEOUT)) { 760 ival = ConfigurationService.getInt(CONF_DEFAULT_MAX_TIMEOUT); 761 } 762 coordJob.setTimeout(ival); 763 764 val = resolveTagContents("concurrency", eAppXml.getChild("controls", eAppXml.getNamespace()), evalNofuncs); 765 if (val == null || val.isEmpty()) { 766 val = ConfigurationService.get(CONF_DEFAULT_CONCURRENCY); 767 } 768 ival = ParamChecker.checkInteger(val, "concurrency"); 769 coordJob.setConcurrency(ival); 770 771 val = resolveTagContents("throttle", eAppXml.getChild("controls", eAppXml.getNamespace()), evalNofuncs); 772 if (val == null || val.isEmpty()) { 773 int defaultThrottle = ConfigurationService.getInt(CONF_DEFAULT_THROTTLE); 774 ival = defaultThrottle; 775 } 776 else { 777 ival = ParamChecker.checkInteger(val, "throttle"); 778 } 779 int maxQueue = ConfigurationService.getInt(CONF_QUEUE_SIZE); 780 float factor = ConfigurationService.getFloat(CONF_MAT_THROTTLING_FACTOR); 781 int maxThrottle = (int) (maxQueue * factor); 782 if (ival > maxThrottle || ival < 1) { 783 ival = maxThrottle; 784 } 785 LOG.debug("max throttle " + ival); 786 coordJob.setMatThrottling(ival); 787 788 val = resolveTagContents("execution", eAppXml.getChild("controls", eAppXml.getNamespace()), evalNofuncs); 789 if (val == "") { 790 val = Execution.FIFO.toString(); 791 } 792 coordJob.setExecutionOrder(Execution.valueOf(val)); 793 String[] acceptedVals = { Execution.LIFO.toString(), Execution.FIFO.toString(), Execution.LAST_ONLY.toString(), 794 Execution.NONE.toString()}; 795 ParamChecker.isMember(val, acceptedVals, "execution"); 796 797 // datasets 798 resolveTagContents("include", eAppXml.getChild("datasets", eAppXml.getNamespace()), evalNofuncs); 799 // for each data set 800 resolveDataSets(eAppXml); 801 HashMap<String, String> dataNameList = new HashMap<String, String>(); 802 resolveIODataset(eAppXml); 803 resolveIOEvents(eAppXml, dataNameList); 804 805 if (CoordUtils.isInputLogicSpecified(eAppXml)) { 806 resolveInputLogic(eAppXml.getChild(CoordInputLogicEvaluator.INPUT_LOGIC, eAppXml.getNamespace()), evalInst, 807 dataNameList); 808 } 809 810 resolveTagContents("app-path", eAppXml.getChild("action", eAppXml.getNamespace()).getChild("workflow", 811 eAppXml.getNamespace()), evalNofuncs); 812 // TODO: If action or workflow tag is missing, NullPointerException will 813 // occur 814 Element configElem = eAppXml.getChild("action", eAppXml.getNamespace()).getChild("workflow", 815 eAppXml.getNamespace()).getChild("configuration", eAppXml.getNamespace()); 816 evalData = CoordELEvaluator.createELEvaluatorForDataEcho(conf, "coord-job-submit-data", dataNameList); 817 if (configElem != null) { 818 for (Element propElem : (List<Element>) configElem.getChildren("property", configElem.getNamespace())) { 819 resolveTagContents("name", propElem, evalData); 820 // Want to check the data-integrity but don't want to modify the 821 // XML 822 // for properties only 823 Element tmpProp = (Element) propElem.clone(); 824 resolveTagContents("value", tmpProp, evalData); 825 } 826 } 827 evalSla = CoordELEvaluator.createELEvaluatorForDataAndConf(conf, "coord-sla-submit", dataNameList); 828 resolveSLA(eAppXml, coordJob); 829 return eAppXml; 830 } 831 832 /** 833 * Resolve SLA events 834 * 835 * @param eAppXml job XML 836 * @param coordJob coordinator job bean 837 * @throws CommandException thrown if failed to resolve sla events 838 */ 839 private void resolveSLA(Element eAppXml, CoordinatorJobBean coordJob) throws CommandException { 840 Element eSla = XmlUtils.getSLAElement(eAppXml.getChild("action", eAppXml.getNamespace())); 841 842 if (eSla != null) { 843 resolveSLAContent(eSla); 844 String slaXml = XmlUtils.prettyPrint(eSla).toString(); 845 try { 846 // EL evaluation 847 slaXml = evalSla.evaluate(slaXml, String.class); 848 // Validate against semantic SXD 849 XmlUtils.validateData(slaXml, SchemaName.SLA_ORIGINAL); 850 } 851 catch (Exception e) { 852 throw new CommandException(ErrorCode.E1004, "Validation ERROR :" + e.getMessage(), e); 853 } 854 } 855 } 856 857 /** 858 * Resolve an SLA value. 859 * 860 * @param elem : XML Element where attribute is defiend 861 */ 862 private void resolveSLAContent(Element elem) { 863 for (Element tagElem : (List<Element>) elem.getChildren()) { 864 if (tagElem != null) { 865 try { 866 String val = CoordELFunctions.evalAndWrap(evalNofuncs, tagElem.getText().trim()); 867 tagElem.setText(val); 868 } 869 catch (Exception e) { 870 LOG.warn("Variable is not defined in job.properties. Here is the message: {0}", e.getMessage()); 871 continue; 872 } 873 } 874 } 875 } 876 877 /** 878 * Resolve input-events/data-in and output-events/data-out tags. 879 * 880 * @param eJobOrg : Job element 881 * @throws CoordinatorJobException thrown if failed to resolve input and output events 882 */ 883 @SuppressWarnings("unchecked") 884 private void resolveIOEvents(Element eJobOrg, HashMap<String, String> dataNameList) throws CoordinatorJobException { 885 // Resolving input-events/data-in 886 // Clone the job and don't update anything in the original 887 Element eJob = (Element) eJobOrg.clone(); 888 Element inputList = eJob.getChild("input-events", eJob.getNamespace()); 889 if (inputList != null) { 890 TreeSet<String> eventNameSet = new TreeSet<String>(); 891 for (Element dataIn : (List<Element>) inputList.getChildren("data-in", eJob.getNamespace())) { 892 String dataInName = dataIn.getAttributeValue("name"); 893 dataNameList.put(dataInName, "data-in"); 894 // check whether there is any duplicate data-in name 895 if (eventNameSet.contains(dataInName)) { 896 throw new RuntimeException("Duplicate dataIn name " + dataInName); 897 } 898 else { 899 eventNameSet.add(dataInName); 900 } 901 resolveTagContents("instance", dataIn, evalInst); 902 resolveTagContents("start-instance", dataIn, evalInst); 903 resolveTagContents("end-instance", dataIn, evalInst); 904 905 } 906 } 907 // Resolving output-events/data-out 908 Element outputList = eJob.getChild("output-events", eJob.getNamespace()); 909 if (outputList != null) { 910 TreeSet<String> eventNameSet = new TreeSet<String>(); 911 for (Element dataOut : (List<Element>) outputList.getChildren("data-out", eJob.getNamespace())) { 912 String dataOutName = dataOut.getAttributeValue("name"); 913 dataNameList.put(dataOutName, "data-out"); 914 // check whether there is any duplicate data-out name 915 if (eventNameSet.contains(dataOutName)) { 916 throw new RuntimeException("Duplicate dataIn name " + dataOutName); 917 } 918 else { 919 eventNameSet.add(dataOutName); 920 } 921 resolveTagContents("instance", dataOut, evalInst); 922 923 } 924 } 925 926 } 927 928 private void resolveInputLogic(Element root, ELEvaluator evalInputLogic, HashMap<String, String> dataNameList) 929 throws Exception { 930 for (Object event : root.getChildren()) { 931 Element inputElement = (Element) event; 932 resolveAttribute("dataset", inputElement, evalInputLogic); 933 String name=resolveAttribute("name", inputElement, evalInputLogic); 934 resolveAttribute("or", inputElement, evalInputLogic); 935 resolveAttribute("and", inputElement, evalInputLogic); 936 resolveAttribute("combine", inputElement, evalInputLogic); 937 938 if (name != null) { 939 dataNameList.put(name, "data-in"); 940 } 941 942 if (!inputElement.getChildren().isEmpty()) { 943 resolveInputLogic(inputElement, evalInputLogic, dataNameList); 944 } 945 } 946 } 947 948 /** 949 * Resolve input-events/dataset and output-events/dataset tags. 950 * 951 * @param eJob : Job element 952 * @throws CoordinatorJobException thrown if failed to resolve input and output events 953 */ 954 @SuppressWarnings("unchecked") 955 private void resolveIODataset(Element eAppXml) throws CoordinatorJobException { 956 // Resolving input-events/data-in 957 Element inputList = eAppXml.getChild("input-events", eAppXml.getNamespace()); 958 if (inputList != null) { 959 for (Element dataIn : (List<Element>) inputList.getChildren("data-in", eAppXml.getNamespace())) { 960 resolveAttribute("dataset", dataIn, evalInst); 961 962 } 963 } 964 // Resolving output-events/data-out 965 Element outputList = eAppXml.getChild("output-events", eAppXml.getNamespace()); 966 if (outputList != null) { 967 for (Element dataOut : (List<Element>) outputList.getChildren("data-out", eAppXml.getNamespace())) { 968 resolveAttribute("dataset", dataOut, evalInst); 969 970 } 971 } 972 973 } 974 975 976 /** 977 * Add an attribute into XML element. 978 * 979 * @param attrName :attribute name 980 * @param elem : Element to add attribute 981 * @param value :Value of attribute 982 */ 983 private void addAnAttribute(String attrName, Element elem, String value) { 984 elem.setAttribute(attrName, value); 985 } 986 987 /** 988 * Resolve datasets using job configuration. 989 * 990 * @param eAppXml : Job Element XML 991 * @throws Exception thrown if failed to resolve datasets 992 */ 993 @SuppressWarnings("unchecked") 994 private void resolveDataSets(Element eAppXml) throws Exception { 995 Element datasetList = eAppXml.getChild("datasets", eAppXml.getNamespace()); 996 if (datasetList != null) { 997 998 List<Element> dsElems = datasetList.getChildren("dataset", eAppXml.getNamespace()); 999 resolveDataSets(dsElems); 1000 resolveTagContents("app-path", eAppXml.getChild("action", eAppXml.getNamespace()).getChild("workflow", 1001 eAppXml.getNamespace()), evalNofuncs); 1002 } 1003 } 1004 1005 /** 1006 * Resolve datasets using job configuration. 1007 * 1008 * @param dsElems : Data set XML element. 1009 * @throws CoordinatorJobException thrown if failed to resolve datasets 1010 */ 1011 private void resolveDataSets(List<Element> dsElems) throws CoordinatorJobException { 1012 for (Element dsElem : dsElems) { 1013 // Setting up default TimeUnit and EndOFDuraion 1014 evalFreq.setVariable("timeunit", TimeUnit.MINUTE); 1015 evalFreq.setVariable("endOfDuration", TimeUnit.NONE); 1016 1017 String val = resolveAttribute("frequency", dsElem, evalFreq); 1018 int ival = ParamChecker.checkInteger(val, "frequency"); 1019 ParamChecker.checkGTZero(ival, "frequency"); 1020 addAnAttribute("freq_timeunit", dsElem, evalFreq.getVariable("timeunit") == null ? TimeUnit.MINUTE 1021 .toString() : ((TimeUnit) evalFreq.getVariable("timeunit")).toString()); 1022 addAnAttribute("end_of_duration", dsElem, evalFreq.getVariable("endOfDuration") == null ? TimeUnit.NONE 1023 .toString() : ((TimeUnit) evalFreq.getVariable("endOfDuration")).toString()); 1024 val = resolveAttribute("initial-instance", dsElem, evalInitialInstance); 1025 ParamChecker.checkDateOozieTZ(val, "initial-instance"); 1026 checkInitialInstance(val); 1027 val = resolveAttribute("timezone", dsElem, evalNofuncs); 1028 ParamChecker.checkTimeZone(val, "timezone"); 1029 resolveTagContents("uri-template", dsElem, evalNofuncs); 1030 resolveTagContents("done-flag", dsElem, evalNofuncs); 1031 } 1032 } 1033 1034 /** 1035 * Resolve the content of a tag. 1036 * 1037 * @param tagName : Tag name of job XML i.e. <timeout> 10 </timeout> 1038 * @param elem : Element where the tag exists. 1039 * @param eval : EL evealuator 1040 * @return Resolved tag content. 1041 * @throws CoordinatorJobException thrown if failed to resolve tag content 1042 */ 1043 @SuppressWarnings("unchecked") 1044 private String resolveTagContents(String tagName, Element elem, ELEvaluator eval) throws CoordinatorJobException { 1045 String ret = ""; 1046 if (elem != null) { 1047 for (Element tagElem : (List<Element>) elem.getChildren(tagName, elem.getNamespace())) { 1048 if (tagElem != null) { 1049 String updated; 1050 try { 1051 updated = CoordELFunctions.evalAndWrap(eval, tagElem.getText().trim()); 1052 1053 } 1054 catch (Exception e) { 1055 throw new CoordinatorJobException(ErrorCode.E1004, e.getMessage(), e); 1056 } 1057 tagElem.removeContent(); 1058 tagElem.addContent(updated); 1059 ret += updated; 1060 } 1061 } 1062 } 1063 return ret; 1064 } 1065 1066 /** 1067 * Resolve an attribute value. 1068 * 1069 * @param attrName : Attribute name. 1070 * @param elem : XML Element where attribute is defiend 1071 * @param eval : ELEvaluator used to resolve 1072 * @return Resolved attribute value 1073 * @throws CoordinatorJobException thrown if failed to resolve an attribute value 1074 */ 1075 private String resolveAttribute(String attrName, Element elem, ELEvaluator eval) throws CoordinatorJobException { 1076 Attribute attr = elem.getAttribute(attrName); 1077 String val = null; 1078 if (attr != null) { 1079 try { 1080 val = CoordELFunctions.evalAndWrap(eval, attr.getValue().trim()); 1081 } 1082 catch (Exception e) { 1083 throw new CoordinatorJobException(ErrorCode.E1004, e.getMessage(), e); 1084 } 1085 attr.setValue(val); 1086 } 1087 return val; 1088 } 1089 1090 /** 1091 * Include referred datasets into XML. 1092 * 1093 * @param resolvedXml : Job XML element. 1094 * @param conf : Job configuration 1095 * @throws CoordinatorJobException thrown if failed to include referred datasets into XML 1096 */ 1097 @SuppressWarnings("unchecked") 1098 protected void includeDataSets(Element resolvedXml, Configuration conf) throws CoordinatorJobException { 1099 Element datasets = resolvedXml.getChild("datasets", resolvedXml.getNamespace()); 1100 Element allDataSets = new Element("all_datasets", resolvedXml.getNamespace()); 1101 List<String> dsList = new ArrayList<String>(); 1102 if (datasets != null) { 1103 for (Element includeElem : (List<Element>) datasets.getChildren("include", datasets.getNamespace())) { 1104 String incDSFile = includeElem.getTextTrim(); 1105 includeOneDSFile(incDSFile, dsList, allDataSets, datasets.getNamespace()); 1106 } 1107 for (Element e : (List<Element>) datasets.getChildren("dataset", datasets.getNamespace())) { 1108 String dsName = e.getAttributeValue("name"); 1109 if (dsList.contains(dsName)) {// Override with this DS 1110 // Remove duplicate 1111 removeDataSet(allDataSets, dsName); 1112 } 1113 else { 1114 dsList.add(dsName); 1115 } 1116 allDataSets.addContent((Element) e.clone()); 1117 } 1118 } 1119 insertDataSet(resolvedXml, allDataSets); 1120 resolvedXml.removeChild("datasets", resolvedXml.getNamespace()); 1121 } 1122 1123 /** 1124 * Include one dataset file. 1125 * 1126 * @param incDSFile : Include data set filename. 1127 * @param dsList :List of dataset names to verify the duplicate. 1128 * @param allDataSets : Element that includes all dataset definitions. 1129 * @param dsNameSpace : Data set name space 1130 * @throws CoordinatorJobException thrown if failed to include one dataset file 1131 */ 1132 @SuppressWarnings("unchecked") 1133 private void includeOneDSFile(String incDSFile, List<String> dsList, Element allDataSets, Namespace dsNameSpace) 1134 throws CoordinatorJobException { 1135 Element tmpDataSets = null; 1136 try { 1137 String dsXml = readDefinition(incDSFile); 1138 LOG.debug("DSFILE :" + incDSFile + "\n" + dsXml); 1139 tmpDataSets = XmlUtils.parseXml(dsXml); 1140 } 1141 catch (JDOMException e) { 1142 LOG.warn("Error parsing included dataset [{0}]. Message [{1}]", incDSFile, e.getMessage()); 1143 throw new CoordinatorJobException(ErrorCode.E0700, e.getMessage()); 1144 } 1145 resolveDataSets(tmpDataSets.getChildren("dataset")); 1146 for (Element e : (List<Element>) tmpDataSets.getChildren("dataset")) { 1147 String dsName = e.getAttributeValue("name"); 1148 if (dsList.contains(dsName)) { 1149 throw new RuntimeException("Duplicate Dataset " + dsName); 1150 } 1151 dsList.add(dsName); 1152 Element tmp = (Element) e.clone(); 1153 // TODO: Don't like to over-write the external/include DS's namespace 1154 tmp.setNamespace(dsNameSpace); 1155 tmp.getChild("uri-template").setNamespace(dsNameSpace); 1156 if (e.getChild("done-flag") != null) { 1157 tmp.getChild("done-flag").setNamespace(dsNameSpace); 1158 } 1159 allDataSets.addContent(tmp); 1160 } 1161 // nested include 1162 for (Element includeElem : (List<Element>) tmpDataSets.getChildren("include", tmpDataSets.getNamespace())) { 1163 String incFile = includeElem.getTextTrim(); 1164 includeOneDSFile(incFile, dsList, allDataSets, dsNameSpace); 1165 } 1166 } 1167 1168 /** 1169 * Remove a dataset from a list of dataset. 1170 * 1171 * @param eDatasets : List of dataset 1172 * @param name : Dataset name to be removed. 1173 */ 1174 @SuppressWarnings("unchecked") 1175 private static void removeDataSet(Element eDatasets, String name) { 1176 for (Element eDataset : (List<Element>) eDatasets.getChildren("dataset", eDatasets.getNamespace())) { 1177 if (eDataset.getAttributeValue("name").equals(name)) { 1178 eDataset.detach(); 1179 return; 1180 } 1181 } 1182 throw new RuntimeException("undefined dataset: " + name); 1183 } 1184 1185 /** 1186 * Read coordinator definition. 1187 * 1188 * @param appPath application path. 1189 * @return coordinator definition. 1190 * @throws CoordinatorJobException thrown if the definition could not be read. 1191 */ 1192 protected String readDefinition(String appPath) throws CoordinatorJobException { 1193 String user = ParamChecker.notEmpty(conf.get(OozieClient.USER_NAME), OozieClient.USER_NAME); 1194 // Configuration confHadoop = CoordUtils.getHadoopConf(conf); 1195 try { 1196 URI uri = new URI(appPath); 1197 LOG.debug("user =" + user); 1198 HadoopAccessorService has = Services.get().get(HadoopAccessorService.class); 1199 Configuration fsConf = has.createConfiguration(uri.getAuthority()); 1200 FileSystem fs = has.createFileSystem(user, uri, fsConf); 1201 Path appDefPath = null; 1202 1203 // app path could be a directory 1204 Path path = new Path(uri.getPath()); 1205 // check file exists for dataset include file, app xml already checked 1206 if (!fs.exists(path)) { 1207 throw new URISyntaxException(path.toString(), "path not existed : " + path.toString()); 1208 } 1209 if (!fs.isFile(path)) { 1210 appDefPath = new Path(path, COORDINATOR_XML_FILE); 1211 } else { 1212 appDefPath = path; 1213 } 1214 1215 Reader reader = new InputStreamReader(fs.open(appDefPath)); 1216 StringWriter writer = new StringWriter(); 1217 IOUtils.copyCharStream(reader, writer); 1218 return writer.toString(); 1219 } 1220 catch (IOException ex) { 1221 LOG.warn("IOException :" + XmlUtils.prettyPrint(conf), ex); 1222 throw new CoordinatorJobException(ErrorCode.E1001, ex.getMessage(), ex); 1223 } 1224 catch (URISyntaxException ex) { 1225 LOG.warn("URISyException :" + ex.getMessage()); 1226 throw new CoordinatorJobException(ErrorCode.E1002, appPath, ex.getMessage(), ex); 1227 } 1228 catch (HadoopAccessorException ex) { 1229 throw new CoordinatorJobException(ex); 1230 } 1231 catch (Exception ex) { 1232 LOG.warn("Exception :", ex); 1233 throw new CoordinatorJobException(ErrorCode.E1001, ex.getMessage(), ex); 1234 } 1235 } 1236 1237 /** 1238 * Write a coordinator job into database 1239 * 1240 *@param appXML : Coordinator definition xml 1241 * @param eJob : XML element of job 1242 * @param coordJob : Coordinator job bean 1243 * @return Job id 1244 * @throws CommandException thrown if unable to save coordinator job to db 1245 */ 1246 protected String storeToDB(String appXML, Element eJob, CoordinatorJobBean coordJob) throws CommandException { 1247 String jobId = Services.get().get(UUIDService.class).generateId(ApplicationType.COORDINATOR); 1248 coordJob.setId(jobId); 1249 1250 coordJob.setAppPath(conf.get(OozieClient.COORDINATOR_APP_PATH)); 1251 coordJob.setCreatedTime(new Date()); 1252 coordJob.setUser(conf.get(OozieClient.USER_NAME)); 1253 String group = ConfigUtils.getWithDeprecatedCheck(conf, OozieClient.JOB_ACL, OozieClient.GROUP_NAME, null); 1254 coordJob.setGroup(group); 1255 coordJob.setConf(XmlUtils.prettyPrint(conf).toString()); 1256 coordJob.setJobXml(XmlUtils.prettyPrint(eJob).toString()); 1257 coordJob.setLastActionNumber(0); 1258 coordJob.setLastModifiedTime(new Date()); 1259 1260 if (!dryrun) { 1261 coordJob.setLastModifiedTime(new Date()); 1262 try { 1263 CoordJobQueryExecutor.getInstance().insert(coordJob); 1264 } 1265 catch (JPAExecutorException jpaee) { 1266 coordJob.setId(null); 1267 coordJob.setStatus(CoordinatorJob.Status.FAILED); 1268 throw new CommandException(jpaee); 1269 } 1270 } 1271 return jobId; 1272 } 1273 1274 /* 1275 * this method checks if the initial-instance specified for a particular 1276 is not a date earlier than the oozie server default Jan 01, 1970 00:00Z UTC 1277 */ 1278 private void checkInitialInstance(String val) throws CoordinatorJobException, IllegalArgumentException { 1279 Date initialInstance, givenInstance; 1280 try { 1281 initialInstance = DateUtils.parseDateUTC("1970-01-01T00:00Z"); 1282 givenInstance = DateUtils.parseDateOozieTZ(val); 1283 } 1284 catch (Exception e) { 1285 throw new IllegalArgumentException("Unable to parse dataset initial-instance string '" + val + 1286 "' to Date object. ",e); 1287 } 1288 if(givenInstance.compareTo(initialInstance) < 0) { 1289 throw new CoordinatorJobException(ErrorCode.E1021, "Dataset initial-instance " + val + 1290 " is earlier than the default initial instance " + DateUtils.formatDateOozieTZ(initialInstance)); 1291 } 1292 } 1293 1294 /* (non-Javadoc) 1295 * @see org.apache.oozie.command.XCommand#getEntityKey() 1296 */ 1297 @Override 1298 public String getEntityKey() { 1299 return null; 1300 } 1301 1302 /* (non-Javadoc) 1303 * @see org.apache.oozie.command.XCommand#isLockRequired() 1304 */ 1305 @Override 1306 protected boolean isLockRequired() { 1307 return false; 1308 } 1309 1310 /* (non-Javadoc) 1311 * @see org.apache.oozie.command.XCommand#loadState() 1312 */ 1313 @Override 1314 protected void loadState() throws CommandException { 1315 jpaService = Services.get().get(JPAService.class); 1316 if (jpaService == null) { 1317 throw new CommandException(ErrorCode.E0610); 1318 } 1319 coordJob = new CoordinatorJobBean(); 1320 if (this.bundleId != null) { 1321 // this coord job is created from bundle 1322 coordJob.setBundleId(this.bundleId); 1323 // first use bundle id if submit thru bundle 1324 LogUtils.setLogInfo(this.bundleId); 1325 } 1326 if (this.coordName != null) { 1327 // this coord job is created from bundle 1328 coordJob.setAppName(this.coordName); 1329 } 1330 setJob(coordJob); 1331 1332 } 1333 1334 /* (non-Javadoc) 1335 * @see org.apache.oozie.command.XCommand#verifyPrecondition() 1336 */ 1337 @Override 1338 protected void verifyPrecondition() throws CommandException { 1339 1340 } 1341 1342 /* (non-Javadoc) 1343 * @see org.apache.oozie.command.TransitionXCommand#notifyParent() 1344 */ 1345 @Override 1346 public void notifyParent() throws CommandException { 1347 // update bundle action 1348 if (coordJob.getBundleId() != null) { 1349 LOG.debug("Updating bundle record: " + coordJob.getBundleId() + " for coord id: " + coordJob.getId()); 1350 BundleStatusUpdateXCommand bundleStatusUpdate = new BundleStatusUpdateXCommand(coordJob, prevStatus); 1351 bundleStatusUpdate.call(); 1352 } 1353 } 1354 1355 /* (non-Javadoc) 1356 * @see org.apache.oozie.command.TransitionXCommand#updateJob() 1357 */ 1358 @Override 1359 public void updateJob() throws CommandException { 1360 } 1361 1362 /* (non-Javadoc) 1363 * @see org.apache.oozie.command.TransitionXCommand#getJob() 1364 */ 1365 @Override 1366 public Job getJob() { 1367 return coordJob; 1368 } 1369 1370 @Override 1371 public void performWrites() throws CommandException { 1372 } 1373}