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.action.hadoop; 020 021import com.google.common.annotations.VisibleForTesting; 022import com.google.common.base.Strings; 023import com.google.common.collect.ImmutableList; 024import com.google.common.collect.ImmutableSet; 025import com.google.common.io.Closeables; 026import com.google.common.primitives.Ints; 027 028import java.io.File; 029import java.io.FileNotFoundException; 030import java.io.IOException; 031import java.io.StringReader; 032import java.net.ConnectException; 033import java.net.URI; 034import java.net.URISyntaxException; 035import java.net.UnknownHostException; 036import java.nio.ByteBuffer; 037import java.text.MessageFormat; 038import java.util.ArrayList; 039import java.util.Arrays; 040import java.util.Collection; 041import java.util.HashMap; 042import java.util.HashSet; 043import java.util.Iterator; 044import java.util.LinkedHashMap; 045import java.util.List; 046import java.util.Map; 047import java.util.Map.Entry; 048 049import org.apache.commons.io.IOUtils; 050import org.apache.hadoop.conf.Configuration; 051import org.apache.hadoop.filecache.DistributedCache; 052import org.apache.hadoop.fs.FileStatus; 053import org.apache.hadoop.fs.FileSystem; 054import org.apache.hadoop.fs.Path; 055import org.apache.hadoop.io.DataOutputBuffer; 056import org.apache.hadoop.ipc.RemoteException; 057import org.apache.hadoop.mapred.JobClient; 058import org.apache.hadoop.mapred.TaskLog; 059import org.apache.hadoop.mapreduce.MRJobConfig; 060import org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager; 061import org.apache.hadoop.mapreduce.v2.util.MRApps; 062import org.apache.hadoop.security.AccessControlException; 063import org.apache.hadoop.security.Credentials; 064import org.apache.hadoop.security.UserGroupInformation; 065import org.apache.hadoop.util.DiskChecker; 066import org.apache.hadoop.util.StringUtils; 067import org.apache.hadoop.yarn.api.ApplicationConstants; 068import org.apache.hadoop.yarn.api.protocolrecords.ApplicationsRequestScope; 069import org.apache.hadoop.yarn.api.records.ApplicationId; 070import org.apache.hadoop.yarn.api.records.ApplicationReport; 071import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; 072import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; 073import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; 074import org.apache.hadoop.yarn.api.records.LocalResource; 075import org.apache.hadoop.yarn.api.records.ResourceRequest; 076import org.apache.hadoop.yarn.api.records.YarnApplicationState; 077import org.apache.hadoop.yarn.client.api.YarnClient; 078import org.apache.hadoop.yarn.client.api.YarnClientApplication; 079import org.apache.hadoop.yarn.conf.YarnConfiguration; 080import org.apache.hadoop.yarn.util.Apps; 081import org.apache.hadoop.yarn.util.ConverterUtils; 082import org.apache.hadoop.yarn.util.Records; 083import org.apache.oozie.WorkflowActionBean; 084import org.apache.oozie.WorkflowJobBean; 085import org.apache.oozie.action.ActionExecutor; 086import org.apache.oozie.action.ActionExecutorException; 087import org.apache.oozie.client.OozieClient; 088import org.apache.oozie.client.WorkflowAction; 089import org.apache.oozie.command.coord.CoordActionStartXCommand; 090import org.apache.oozie.command.wf.WorkflowXCommand; 091import org.apache.oozie.service.ConfigurationService; 092import org.apache.oozie.service.HadoopAccessorException; 093import org.apache.oozie.service.HadoopAccessorService; 094import org.apache.oozie.service.Services; 095import org.apache.oozie.service.ShareLibService; 096import org.apache.oozie.service.URIHandlerService; 097import org.apache.oozie.service.WorkflowAppService; 098import org.apache.oozie.util.ClasspathUtils; 099import org.apache.oozie.util.ELEvaluationException; 100import org.apache.oozie.util.ELEvaluator; 101import org.apache.oozie.util.FSUtils; 102import org.apache.oozie.util.JobUtils; 103import org.apache.oozie.util.LogUtils; 104import org.apache.oozie.util.PropertiesUtils; 105import org.apache.oozie.util.XConfiguration; 106import org.apache.oozie.util.XLog; 107import org.apache.oozie.util.XmlUtils; 108import org.jdom.Element; 109import org.jdom.JDOMException; 110import org.jdom.Namespace; 111 112import java.util.Objects; 113import java.util.Properties; 114import java.util.Set; 115 116import com.google.common.base.Preconditions; 117import com.google.common.collect.ImmutableMap; 118 119public class JavaActionExecutor extends ActionExecutor { 120 public static final String RUNNING = "RUNNING"; 121 public static final String SUCCEEDED = "SUCCEEDED"; 122 public static final String KILLED = "KILLED"; 123 public static final String FAILED = "FAILED"; 124 public static final String FAILED_KILLED = "FAILED/KILLED"; 125 public static final String HADOOP_YARN_RM = "yarn.resourcemanager.address"; 126 public static final String HADOOP_NAME_NODE = "fs.default.name"; 127 public static final String OOZIE_COMMON_LIBDIR = "oozie"; 128 129 public static final String DEFAULT_LAUNCHER_VCORES = "oozie.launcher.default.vcores"; 130 public static final String DEFAULT_LAUNCHER_MEMORY_MB = "oozie.launcher.default.memory.mb"; 131 public static final String DEFAULT_LAUNCHER_PRIORITY = "oozie.launcher.default.priority"; 132 public static final String DEFAULT_LAUNCHER_QUEUE = "oozie.launcher.default.queue"; 133 public static final String DEFAULT_LAUNCHER_MAX_ATTEMPTS = "oozie.launcher.default.max.attempts"; 134 public static final String LAUNCER_MODIFY_ACL = "oozie.launcher.modify.acl"; 135 public static final String LAUNCER_VIEW_ACL = "oozie.launcher.view.acl"; 136 137 public static final String MAPREDUCE_TO_CLASSPATH = "mapreduce.needed.for"; 138 public static final String OOZIE_LAUNCHER_ADD_MAPREDUCE_TO_CLASSPATH_PROPERTY = ActionExecutor.CONF_PREFIX 139 + MAPREDUCE_TO_CLASSPATH; 140 141 public static final String MAX_EXTERNAL_STATS_SIZE = "oozie.external.stats.max.size"; 142 public static final String ACL_VIEW_JOB = "mapreduce.job.acl-view-job"; 143 public static final String ACL_MODIFY_JOB = "mapreduce.job.acl-modify-job"; 144 public static final String HADOOP_YARN_TIMELINE_SERVICE_ENABLED = "yarn.timeline-service.enabled"; 145 public static final String HADOOP_YARN_UBER_MODE = "mapreduce.job.ubertask.enable"; 146 public static final String OOZIE_ACTION_LAUNCHER_PREFIX = ActionExecutor.CONF_PREFIX + "launcher."; 147 public static final String HADOOP_YARN_KILL_CHILD_JOBS_ON_AMRESTART = 148 OOZIE_ACTION_LAUNCHER_PREFIX + "am.restart.kill.childjobs"; 149 public static final String HADOOP_MAP_MEMORY_MB = "mapreduce.map.memory.mb"; 150 public static final String HADOOP_CHILD_JAVA_OPTS = "mapred.child.java.opts"; 151 public static final String HADOOP_MAP_JAVA_OPTS = "mapreduce.map.java.opts"; 152 public static final String HADOOP_REDUCE_JAVA_OPTS = "mapreduce.reduce.java.opts"; 153 public static final String HADOOP_CHILD_JAVA_ENV = "mapred.child.env"; 154 public static final String HADOOP_MAP_JAVA_ENV = "mapreduce.map.env"; 155 public static final String HADOOP_JOB_CLASSLOADER = "mapreduce.job.classloader"; 156 public static final String HADOOP_USER_CLASSPATH_FIRST = "mapreduce.user.classpath.first"; 157 public static final String OOZIE_CREDENTIALS_SKIP = "oozie.credentials.skip"; 158 public static final String YARN_AM_RESOURCE_MB = "yarn.app.mapreduce.am.resource.mb"; 159 public static final String YARN_AM_COMMAND_OPTS = "yarn.app.mapreduce.am.command-opts"; 160 public static final String YARN_AM_ENV = "yarn.app.mapreduce.am.env"; 161 public static final int YARN_MEMORY_MB_MIN = 512; 162 163 private static final String JAVA_MAIN_CLASS_NAME = "org.apache.oozie.action.hadoop.JavaMain"; 164 private static final String HADOOP_JOB_NAME = "mapred.job.name"; 165 static final Set<String> DISALLOWED_PROPERTIES = ImmutableSet.of( 166 OozieClient.USER_NAME, MRJobConfig.USER_NAME, HADOOP_NAME_NODE, HADOOP_YARN_RM 167 ); 168 private static final String OOZIE_ACTION_NAME = "oozie.action.name"; 169 private final static String ACTION_SHARELIB_FOR = "oozie.action.sharelib.for."; 170 171 private static int maxActionOutputLen; 172 private static int maxExternalStatsSize; 173 private static int maxFSGlobMax; 174 175 protected static final String HADOOP_USER = "user.name"; 176 177 protected XLog LOG = XLog.getLog(getClass()); 178 private static final String JAVA_TMP_DIR_SETTINGS = "-Djava.io.tmpdir="; 179 180 public XConfiguration workflowConf = null; 181 182 public JavaActionExecutor() { 183 this("java"); 184 } 185 186 protected JavaActionExecutor(String type) { 187 super(type); 188 } 189 190 public static List<Class<?>> getCommonLauncherClasses() { 191 List<Class<?>> classes = new ArrayList<Class<?>>(); 192 classes.add(LauncherMain.class); 193 classes.addAll(Services.get().get(URIHandlerService.class).getClassesForLauncher()); 194 classes.add(LauncherAM.class); 195 classes.add(LauncherAMCallbackNotifier.class); 196 return classes; 197 } 198 199 public List<Class<?>> getLauncherClasses() { 200 List<Class<?>> classes = new ArrayList<Class<?>>(); 201 try { 202 classes.add(Class.forName(JAVA_MAIN_CLASS_NAME)); 203 } 204 catch (ClassNotFoundException e) { 205 throw new RuntimeException("Class not found", e); 206 } 207 return classes; 208 } 209 210 @Override 211 public void initActionType() { 212 super.initActionType(); 213 maxActionOutputLen = ConfigurationService.getInt(LauncherAM.CONF_OOZIE_ACTION_MAX_OUTPUT_DATA); 214 //Get the limit for the maximum allowed size of action stats 215 maxExternalStatsSize = ConfigurationService.getInt(JavaActionExecutor.MAX_EXTERNAL_STATS_SIZE); 216 maxExternalStatsSize = (maxExternalStatsSize == -1) ? Integer.MAX_VALUE : maxExternalStatsSize; 217 //Get the limit for the maximum number of globbed files/dirs for FS operation 218 maxFSGlobMax = ConfigurationService.getInt(LauncherAMUtils.CONF_OOZIE_ACTION_FS_GLOB_MAX); 219 220 registerError(UnknownHostException.class.getName(), ActionExecutorException.ErrorType.TRANSIENT, "JA001"); 221 registerError(AccessControlException.class.getName(), ActionExecutorException.ErrorType.NON_TRANSIENT, 222 "JA002"); 223 registerError(DiskChecker.DiskOutOfSpaceException.class.getName(), 224 ActionExecutorException.ErrorType.NON_TRANSIENT, "JA003"); 225 registerError(org.apache.hadoop.hdfs.protocol.QuotaExceededException.class.getName(), 226 ActionExecutorException.ErrorType.NON_TRANSIENT, "JA004"); 227 registerError(org.apache.hadoop.hdfs.server.namenode.SafeModeException.class.getName(), 228 ActionExecutorException.ErrorType.NON_TRANSIENT, "JA005"); 229 registerError(ConnectException.class.getName(), ActionExecutorException.ErrorType.TRANSIENT, " JA006"); 230 registerError(JDOMException.class.getName(), ActionExecutorException.ErrorType.ERROR, "JA007"); 231 registerError(FileNotFoundException.class.getName(), ActionExecutorException.ErrorType.ERROR, "JA008"); 232 registerError(IOException.class.getName(), ActionExecutorException.ErrorType.TRANSIENT, "JA009"); 233 } 234 235 236 /** 237 * Get the maximum allowed size of stats 238 * 239 * @return maximum size of stats 240 */ 241 public static int getMaxExternalStatsSize() { 242 return maxExternalStatsSize; 243 } 244 245 static void checkForDisallowedProps(Configuration conf, String confName) throws ActionExecutorException { 246 for (String prop : DISALLOWED_PROPERTIES) { 247 if (conf.get(prop) != null) { 248 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "JA010", 249 "Property [{0}] not allowed in action [{1}] configuration", prop, confName); 250 } 251 } 252 } 253 254 public Configuration createBaseHadoopConf(Context context, Element actionXml) { 255 return createBaseHadoopConf(context, actionXml, true); 256 } 257 258 protected Configuration createBaseHadoopConf(Context context, Element actionXml, boolean loadResources) { 259 260 Namespace ns = actionXml.getNamespace(); 261 String resourceManager; 262 final Element resourceManagerTag = actionXml.getChild("resource-manager", ns); 263 if (resourceManagerTag != null) { 264 resourceManager = resourceManagerTag.getTextTrim(); 265 } 266 else { 267 resourceManager = actionXml.getChild("job-tracker", ns).getTextTrim(); 268 } 269 270 String nameNode = actionXml.getChild("name-node", ns).getTextTrim(); 271 Configuration conf = null; 272 if (loadResources) { 273 conf = Services.get().get(HadoopAccessorService.class).createConfiguration(resourceManager); 274 } 275 else { 276 conf = new Configuration(false); 277 } 278 279 conf.set(HADOOP_USER, context.getProtoActionConf().get(WorkflowAppService.HADOOP_USER)); 280 conf.set(HADOOP_YARN_RM, resourceManager); 281 conf.set(HADOOP_NAME_NODE, nameNode); 282 conf.set("mapreduce.fileoutputcommitter.marksuccessfuljobs", "true"); 283 284 // FIXME - think about this! 285 Element e = actionXml.getChild("config-class", ns); 286 if (e != null) { 287 conf.set(LauncherAMUtils.OOZIE_ACTION_CONFIG_CLASS, e.getTextTrim()); 288 } 289 290 return conf; 291 } 292 293 protected Configuration loadHadoopDefaultResources(Context context, Element actionXml) { 294 return createBaseHadoopConf(context, actionXml); 295 } 296 297 Configuration setupLauncherConf(Configuration conf, Element actionXml, Path appPath, Context context) 298 throws ActionExecutorException { 299 try { 300 Namespace ns = actionXml.getNamespace(); 301 XConfiguration launcherConf = new XConfiguration(); 302 // Inject action defaults for launcher 303 HadoopAccessorService has = Services.get().get(HadoopAccessorService.class); 304 XConfiguration actionDefaultConf = has.createActionDefaultConf(conf.get(HADOOP_YARN_RM), getType()); 305 306 new LauncherConfigurationInjector(actionDefaultConf).inject(launcherConf); 307 308 // Inject <job-xml> and <configuration> for launcher 309 try { 310 parseJobXmlAndConfiguration(context, actionXml, appPath, launcherConf, true); 311 } catch (HadoopAccessorException ex) { 312 throw convertException(ex); 313 } catch (URISyntaxException ex) { 314 throw convertException(ex); 315 } 316 XConfiguration.copy(launcherConf, conf); 317 // Inject config-class for launcher to use for action 318 Element e = actionXml.getChild("config-class", ns); 319 if (e != null) { 320 conf.set(LauncherAMUtils.OOZIE_ACTION_CONFIG_CLASS, e.getTextTrim()); 321 } 322 checkForDisallowedProps(launcherConf, "launcher configuration"); 323 return conf; 324 } 325 catch (IOException ex) { 326 throw convertException(ex); 327 } 328 } 329 330 void injectLauncherTimelineServiceEnabled(Configuration launcherConf, Configuration actionConf) { 331 // Getting delegation token for ATS. If tez-site.xml is present in distributed cache, turn on timeline service. 332 if (actionConf.get("oozie.launcher." + HADOOP_YARN_TIMELINE_SERVICE_ENABLED) == null 333 && ConfigurationService.getBoolean(OOZIE_ACTION_LAUNCHER_PREFIX + HADOOP_YARN_TIMELINE_SERVICE_ENABLED)) { 334 String cacheFiles = launcherConf.get("mapred.cache.files"); 335 if (cacheFiles != null && cacheFiles.contains("tez-site.xml")) { 336 launcherConf.setBoolean(HADOOP_YARN_TIMELINE_SERVICE_ENABLED, true); 337 } 338 } 339 } 340 341 public static void parseJobXmlAndConfiguration(Context context, Element element, Path appPath, Configuration conf) 342 throws IOException, ActionExecutorException, HadoopAccessorException, URISyntaxException { 343 parseJobXmlAndConfiguration(context, element, appPath, conf, false); 344 } 345 346 public static void parseJobXmlAndConfiguration(Context context, Element element, Path appPath, Configuration conf, 347 boolean isLauncher) throws IOException, ActionExecutorException, HadoopAccessorException, URISyntaxException { 348 Namespace ns = element.getNamespace(); 349 @SuppressWarnings("unchecked") 350 Iterator<Element> it = element.getChildren("job-xml", ns).iterator(); 351 HashMap<String, FileSystem> filesystemsMap = new HashMap<String, FileSystem>(); 352 HadoopAccessorService has = Services.get().get(HadoopAccessorService.class); 353 while (it.hasNext()) { 354 Element e = it.next(); 355 String jobXml = e.getTextTrim(); 356 Path pathSpecified = new Path(jobXml); 357 Path path = pathSpecified.isAbsolute() ? pathSpecified : new Path(appPath, jobXml); 358 FileSystem fs; 359 if (filesystemsMap.containsKey(path.toUri().getAuthority())) { 360 fs = filesystemsMap.get(path.toUri().getAuthority()); 361 } 362 else { 363 if (path.toUri().getAuthority() != null) { 364 fs = has.createFileSystem(context.getWorkflow().getUser(), path.toUri(), 365 has.createConfiguration(path.toUri().getAuthority())); 366 } 367 else { 368 fs = context.getAppFileSystem(); 369 } 370 filesystemsMap.put(path.toUri().getAuthority(), fs); 371 } 372 Configuration jobXmlConf = new XConfiguration(fs.open(path)); 373 try { 374 String jobXmlConfString = XmlUtils.prettyPrint(jobXmlConf).toString(); 375 jobXmlConfString = XmlUtils.removeComments(jobXmlConfString); 376 jobXmlConfString = context.getELEvaluator().evaluate(jobXmlConfString, String.class); 377 jobXmlConf = new XConfiguration(new StringReader(jobXmlConfString)); 378 } 379 catch (ELEvaluationException ex) { 380 throw new ActionExecutorException(ActionExecutorException.ErrorType.TRANSIENT, "EL_EVAL_ERROR", ex 381 .getMessage(), ex); 382 } 383 catch (Exception ex) { 384 context.setErrorInfo("EL_ERROR", ex.getMessage()); 385 } 386 checkForDisallowedProps(jobXmlConf, "job-xml"); 387 if (isLauncher) { 388 new LauncherConfigurationInjector(jobXmlConf).inject(conf); 389 } else { 390 XConfiguration.copy(jobXmlConf, conf); 391 } 392 } 393 Element e = element.getChild("configuration", ns); 394 if (e != null) { 395 String strConf = XmlUtils.prettyPrint(e).toString(); 396 XConfiguration inlineConf = new XConfiguration(new StringReader(strConf)); 397 checkForDisallowedProps(inlineConf, "inline configuration"); 398 if (isLauncher) { 399 new LauncherConfigurationInjector(inlineConf).inject(conf); 400 } else { 401 XConfiguration.copy(inlineConf, conf); 402 } 403 } 404 } 405 406 Configuration setupActionConf(Configuration actionConf, Context context, Element actionXml, Path appPath) 407 throws ActionExecutorException { 408 try { 409 HadoopAccessorService has = Services.get().get(HadoopAccessorService.class); 410 XConfiguration actionDefaults = has.createActionDefaultConf(actionConf.get(HADOOP_YARN_RM), getType()); 411 XConfiguration.copy(actionDefaults, actionConf); 412 has.checkSupportedFilesystem(appPath.toUri()); 413 414 // Set the Java Main Class for the Java action to give to the Java launcher 415 setJavaMain(actionConf, actionXml); 416 417 parseJobXmlAndConfiguration(context, actionXml, appPath, actionConf); 418 419 // set cancel.delegation.token in actionConf that child job doesn't cancel delegation token 420 actionConf.setBoolean("mapreduce.job.complete.cancel.delegation.tokens", false); 421 setRootLoggerLevel(actionConf); 422 return actionConf; 423 } 424 catch (IOException ex) { 425 throw convertException(ex); 426 } 427 catch (HadoopAccessorException ex) { 428 throw convertException(ex); 429 } 430 catch (URISyntaxException ex) { 431 throw convertException(ex); 432 } 433 } 434 435 /** 436 * Set root log level property in actionConf 437 * @param actionConf 438 */ 439 void setRootLoggerLevel(Configuration actionConf) { 440 String oozieActionTypeRootLogger = "oozie.action." + getType() + LauncherAMUtils.ROOT_LOGGER_LEVEL; 441 String oozieActionRootLogger = "oozie.action." + LauncherAMUtils.ROOT_LOGGER_LEVEL; 442 443 // check if root log level has already mentioned in action configuration 444 String rootLogLevel = actionConf.get(oozieActionTypeRootLogger, actionConf.get(oozieActionRootLogger)); 445 if (rootLogLevel != null) { 446 // root log level is mentioned in action configuration 447 return; 448 } 449 450 // set the root log level which is mentioned in oozie default 451 rootLogLevel = ConfigurationService.get(oozieActionTypeRootLogger); 452 if (rootLogLevel != null && rootLogLevel.length() > 0) { 453 actionConf.set(oozieActionRootLogger, rootLogLevel); 454 } 455 else { 456 rootLogLevel = ConfigurationService.get(oozieActionRootLogger); 457 if (rootLogLevel != null && rootLogLevel.length() > 0) { 458 actionConf.set(oozieActionRootLogger, rootLogLevel); 459 } 460 } 461 } 462 463 Configuration addToCache(Configuration conf, Path appPath, String filePath, boolean archive) 464 throws ActionExecutorException { 465 466 URI uri = null; 467 try { 468 uri = new URI(getTrimmedEncodedPath(filePath)); 469 URI baseUri = appPath.toUri(); 470 if (uri.getScheme() == null) { 471 String resolvedPath = uri.getPath(); 472 if (!resolvedPath.startsWith("/")) { 473 resolvedPath = baseUri.getPath() + "/" + resolvedPath; 474 } 475 uri = new URI(baseUri.getScheme(), baseUri.getAuthority(), resolvedPath, uri.getQuery(), uri.getFragment()); 476 } 477 if (archive) { 478 DistributedCache.addCacheArchive(uri.normalize(), conf); 479 } 480 else { 481 String fileName = filePath.substring(filePath.lastIndexOf("/") + 1); 482 if (fileName.endsWith(".so") || fileName.contains(".so.")) { // .so files 483 uri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), uri.getQuery(), fileName); 484 DistributedCache.addCacheFile(uri.normalize(), conf); 485 } 486 else if (fileName.endsWith(".jar")) { // .jar files 487 if (!fileName.contains("#")) { 488 String user = conf.get("user.name"); 489 490 if (FSUtils.isNotLocalFile(fileName)) { 491 Path pathToAdd = new Path(uri.normalize()); 492 Services.get().get(HadoopAccessorService.class).addFileToClassPath(user, pathToAdd, conf); 493 } 494 } 495 else { 496 DistributedCache.addCacheFile(uri.normalize(), conf); 497 } 498 } 499 else { // regular files 500 if (!fileName.contains("#")) { 501 uri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), uri.getQuery(), fileName); 502 } 503 DistributedCache.addCacheFile(uri.normalize(), conf); 504 } 505 } 506 DistributedCache.createSymlink(conf); 507 return conf; 508 } 509 catch (Exception ex) { 510 LOG.debug("Errors when add to DistributedCache. Path=" + 511 Objects.toString(uri, "<null>") + ", archive=" + archive + ", conf=" + 512 XmlUtils.prettyPrint(conf).toString()); 513 throw convertException(ex); 514 } 515 } 516 517 public void prepareActionDir(FileSystem actionFs, Context context) throws ActionExecutorException { 518 try { 519 Path actionDir = context.getActionDir(); 520 Path tempActionDir = new Path(actionDir.getParent(), actionDir.getName() + ".tmp"); 521 if (!actionFs.exists(actionDir)) { 522 try { 523 actionFs.mkdirs(tempActionDir); 524 actionFs.rename(tempActionDir, actionDir); 525 } 526 catch (IOException ex) { 527 actionFs.delete(tempActionDir, true); 528 actionFs.delete(actionDir, true); 529 throw ex; 530 } 531 } 532 } 533 catch (Exception ex) { 534 throw convertException(ex); 535 } 536 } 537 538 void cleanUpActionDir(FileSystem actionFs, Context context) throws ActionExecutorException { 539 try { 540 Path actionDir = context.getActionDir(); 541 if (!context.getProtoActionConf().getBoolean(WorkflowXCommand.KEEP_WF_ACTION_DIR, false) 542 && actionFs.exists(actionDir)) { 543 actionFs.delete(actionDir, true); 544 } 545 } 546 catch (Exception ex) { 547 throw convertException(ex); 548 } 549 } 550 551 protected void addShareLib(Configuration conf, String[] actionShareLibNames) 552 throws ActionExecutorException { 553 Set<String> confSet = new HashSet<String>(Arrays.asList(getShareLibFilesForActionConf() == null ? new String[0] 554 : getShareLibFilesForActionConf())); 555 556 Set<Path> sharelibList = new HashSet<Path>(); 557 558 if (actionShareLibNames != null) { 559 try { 560 ShareLibService shareLibService = Services.get().get(ShareLibService.class); 561 FileSystem fs = shareLibService.getFileSystem(); 562 if (fs != null) { 563 for (String actionShareLibName : actionShareLibNames) { 564 List<Path> listOfPaths = shareLibService.getShareLibJars(actionShareLibName); 565 if (listOfPaths != null && !listOfPaths.isEmpty()) { 566 for (Path actionLibPath : listOfPaths) { 567 String fragmentName = new URI(actionLibPath.toString()).getFragment(); 568 String fileName = fragmentName == null ? actionLibPath.getName() : fragmentName; 569 if (confSet.contains(fileName)) { 570 Configuration jobXmlConf = shareLibService.getShareLibConf(actionShareLibName, 571 actionLibPath); 572 if (jobXmlConf != null) { 573 checkForDisallowedProps(jobXmlConf, actionLibPath.getName()); 574 XConfiguration.injectDefaults(jobXmlConf, conf); 575 LOG.trace("Adding properties of " + actionLibPath + " to job conf"); 576 } 577 } 578 else { 579 // Filtering out duplicate jars or files 580 sharelibList.add(new Path(actionLibPath.toUri()) { 581 @Override 582 public int hashCode() { 583 return getName().hashCode(); 584 } 585 @Override 586 public String getName() { 587 try { 588 return (new URI(toString())).getFragment() == null ? new Path(toUri()).getName() 589 : (new URI(toString())).getFragment(); 590 } 591 catch (URISyntaxException e) { 592 throw new RuntimeException(e); 593 } 594 } 595 @Override 596 public boolean equals(Object input) { 597 if (input == null) { 598 return false; 599 } 600 if (input == this) { 601 return true; 602 } 603 if (!(input instanceof Path)) { 604 return false; 605 } 606 return getName().equals(((Path) input).getName()); 607 } 608 }); 609 } 610 } 611 } 612 } 613 } 614 addLibPathsToCache(conf, sharelibList); 615 } 616 catch (URISyntaxException ex) { 617 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "Error configuring sharelib", 618 ex.getMessage()); 619 } 620 catch (IOException ex) { 621 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "It should never happen", 622 ex.getMessage()); 623 } 624 } 625 } 626 627 protected void addSystemShareLibForAction(Configuration conf) throws ActionExecutorException { 628 ShareLibService shareLibService = Services.get().get(ShareLibService.class); 629 // ShareLibService is null for test cases 630 if (shareLibService != null) { 631 try { 632 List<Path> listOfPaths = shareLibService.getSystemLibJars(JavaActionExecutor.OOZIE_COMMON_LIBDIR); 633 if (listOfPaths.isEmpty()) { 634 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "EJ001", 635 "Could not locate Oozie sharelib"); 636 } 637 addLibPathsToClassPath(conf, listOfPaths); 638 addLibPathsToClassPath(conf, shareLibService.getSystemLibJars(getType())); 639 } 640 catch (IOException ex) { 641 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "It should never happen", 642 ex.getMessage()); 643 } 644 } 645 } 646 647 private void addLibPathsToClassPath(Configuration conf, List<Path> listOfPaths) 648 throws IOException, ActionExecutorException { 649 addLibPathsToClassPathOrCache(conf, listOfPaths, false); 650 } 651 652 private void addLibPathsToCache(Configuration conf, Set<Path> sharelibList) 653 throws IOException, ActionExecutorException { 654 addLibPathsToClassPathOrCache(conf, sharelibList, true); 655 } 656 657 658 private void addLibPathsToClassPathOrCache(Configuration conf, Collection<Path> sharelibList, boolean isAddToCache) 659 throws IOException, ActionExecutorException { 660 661 for (Path libPath : sharelibList) { 662 if (FSUtils.isLocalFile(libPath.toString())) { 663 conf = ClasspathUtils.addToClasspathFromLocalShareLib(conf, libPath); 664 } 665 else { 666 if (isAddToCache) { 667 addToCache(conf, libPath, libPath.toUri().getPath(), false); 668 } 669 else { 670 FileSystem fs = libPath.getFileSystem(conf); 671 JobUtils.addFileToClassPath(libPath, conf, fs); 672 DistributedCache.createSymlink(conf); 673 } 674 } 675 } 676 } 677 678 protected void addActionLibs(Path appPath, Configuration conf) throws ActionExecutorException { 679 String[] actionLibsStrArr = conf.getStrings("oozie.launcher.oozie.libpath"); 680 if (actionLibsStrArr != null) { 681 try { 682 for (String actionLibsStr : actionLibsStrArr) { 683 actionLibsStr = actionLibsStr.trim(); 684 if (actionLibsStr.length() > 0) 685 { 686 Path actionLibsPath = new Path(actionLibsStr); 687 String user = conf.get("user.name"); 688 FileSystem fs = Services.get().get(HadoopAccessorService.class).createFileSystem(user, 689 appPath.toUri(), conf); 690 if (fs.exists(actionLibsPath)) { 691 FileStatus[] files = fs.listStatus(actionLibsPath); 692 for (FileStatus file : files) { 693 addToCache(conf, appPath, file.getPath().toUri().getPath(), false); 694 } 695 } 696 } 697 } 698 } 699 catch (HadoopAccessorException ex){ 700 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, 701 ex.getErrorCode().toString(), ex.getMessage()); 702 } 703 catch (IOException ex){ 704 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, 705 "It should never happen", ex.getMessage()); 706 } 707 } 708 } 709 710 @SuppressWarnings("unchecked") 711 public void setLibFilesArchives(Context context, Element actionXml, Path appPath, Configuration conf) 712 throws ActionExecutorException { 713 Configuration proto = context.getProtoActionConf(); 714 715 // Workflow lib/ 716 String[] paths = proto.getStrings(WorkflowAppService.APP_LIB_PATH_LIST); 717 if (paths != null) { 718 for (String path : paths) { 719 addToCache(conf, appPath, path, false); 720 } 721 } 722 723 // Action libs 724 addActionLibs(appPath, conf); 725 726 // files and archives defined in the action 727 for (Element eProp : (List<Element>) actionXml.getChildren()) { 728 if (eProp.getName().equals("file")) { 729 String[] filePaths = eProp.getTextTrim().split(","); 730 for (String path : filePaths) { 731 addToCache(conf, appPath, path, false); 732 } 733 } 734 else if (eProp.getName().equals("archive")) { 735 String[] archivePaths = eProp.getTextTrim().split(","); 736 for (String path : archivePaths){ 737 addToCache(conf, appPath, path.trim(), true); 738 } 739 } 740 } 741 742 addAllShareLibs(appPath, conf, context, actionXml); 743 } 744 745 @VisibleForTesting 746 protected static String getTrimmedEncodedPath(String path) { 747 return path.trim().replace(" ", "%20"); 748 } 749 750 // Adds action specific share libs and common share libs 751 private void addAllShareLibs(Path appPath, Configuration conf, Context context, Element actionXml) 752 throws ActionExecutorException { 753 // Add action specific share libs 754 addActionShareLib(appPath, conf, context, actionXml); 755 // Add common sharelibs for Oozie and launcher jars 756 addSystemShareLibForAction(conf); 757 } 758 759 private void addActionShareLib(Path appPath, Configuration conf, Context context, Element actionXml) 760 throws ActionExecutorException { 761 XConfiguration wfJobConf = null; 762 try { 763 wfJobConf = getWorkflowConf(context); 764 } 765 catch (IOException ioe) { 766 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "It should never happen", 767 ioe.getMessage()); 768 } 769 // Action sharelibs are only added if user has specified to use system libpath 770 if (conf.get(OozieClient.USE_SYSTEM_LIBPATH) == null) { 771 if (wfJobConf.getBoolean(OozieClient.USE_SYSTEM_LIBPATH, 772 ConfigurationService.getBoolean(OozieClient.USE_SYSTEM_LIBPATH))) { 773 // add action specific sharelibs 774 addShareLib(conf, getShareLibNames(context, actionXml, conf)); 775 } 776 } 777 else { 778 if (conf.getBoolean(OozieClient.USE_SYSTEM_LIBPATH, false)) { 779 // add action specific sharelibs 780 addShareLib(conf, getShareLibNames(context, actionXml, conf)); 781 } 782 } 783 } 784 785 786 protected String getLauncherMain(Configuration launcherConf, Element actionXml) { 787 return launcherConf.get(LauncherAM.CONF_OOZIE_ACTION_MAIN_CLASS, JavaMain.class.getName()); 788 } 789 790 private void setJavaMain(Configuration actionConf, Element actionXml) { 791 Namespace ns = actionXml.getNamespace(); 792 Element e = actionXml.getChild("main-class", ns); 793 if (e != null) { 794 actionConf.set(JavaMain.JAVA_MAIN_CLASS, e.getTextTrim()); 795 } 796 } 797 798 private static final String QUEUE_NAME = "mapred.job.queue.name"; 799 800 private static final Set<String> SPECIAL_PROPERTIES = new HashSet<String>(); 801 802 static { 803 SPECIAL_PROPERTIES.add(QUEUE_NAME); 804 SPECIAL_PROPERTIES.add(ACL_VIEW_JOB); 805 SPECIAL_PROPERTIES.add(ACL_MODIFY_JOB); 806 } 807 808 @SuppressWarnings("unchecked") 809 Configuration createLauncherConf(FileSystem actionFs, Context context, WorkflowAction action, Element actionXml, 810 Configuration actionConf) throws ActionExecutorException { 811 try { 812 813 // app path could be a file 814 Path appPathRoot = new Path(context.getWorkflow().getAppPath()); 815 if (actionFs.isFile(appPathRoot)) { 816 appPathRoot = appPathRoot.getParent(); 817 } 818 819 // launcher job configuration 820 Configuration launcherJobConf = createBaseHadoopConf(context, actionXml); 821 // cancel delegation token on a launcher job which stays alive till child job(s) finishes 822 // otherwise (in mapred action), doesn't cancel not to disturb running child job 823 launcherJobConf.setBoolean("mapreduce.job.complete.cancel.delegation.tokens", true); 824 setupLauncherConf(launcherJobConf, actionXml, appPathRoot, context); 825 826 // Properties for when a launcher job's AM gets restarted 827 if (ConfigurationService.getBoolean(HADOOP_YARN_KILL_CHILD_JOBS_ON_AMRESTART)) { 828 // launcher time filter is required to prune the search of launcher tag. 829 // Setting coordinator action nominal time as launcher time as it child job cannot launch before nominal 830 // time. Workflow created time is good enough when workflow is running independently or workflow is 831 // rerunning from failed node. 832 long launcherTime = System.currentTimeMillis(); 833 String coordActionNominalTime = context.getProtoActionConf().get( 834 CoordActionStartXCommand.OOZIE_COORD_ACTION_NOMINAL_TIME); 835 if (coordActionNominalTime != null) { 836 launcherTime = Long.parseLong(coordActionNominalTime); 837 } 838 else if (context.getWorkflow().getCreatedTime() != null) { 839 launcherTime = context.getWorkflow().getCreatedTime().getTime(); 840 } 841 String actionYarnTag = getActionYarnTag(getWorkflowConf(context), context.getWorkflow(), action); 842 LauncherHelper.setupYarnRestartHandling(launcherJobConf, actionConf, actionYarnTag, launcherTime); 843 } 844 else { 845 LOG.info(MessageFormat.format("{0} is set to false, not setting YARN restart properties", 846 HADOOP_YARN_KILL_CHILD_JOBS_ON_AMRESTART)); 847 } 848 849 String actionShareLibProperty = actionConf.get(ACTION_SHARELIB_FOR + getType()); 850 if (actionShareLibProperty != null) { 851 launcherJobConf.set(ACTION_SHARELIB_FOR + getType(), actionShareLibProperty); 852 } 853 setLibFilesArchives(context, actionXml, appPathRoot, launcherJobConf); 854 855 // Inject Oozie job information if enabled. 856 injectJobInfo(launcherJobConf, actionConf, context, action); 857 858 injectLauncherCallback(context, launcherJobConf); 859 860 String jobId = context.getWorkflow().getId(); 861 String actionId = action.getId(); 862 Path actionDir = context.getActionDir(); 863 String recoveryId = context.getRecoveryId(); 864 865 // Getting the prepare XML from the action XML 866 Namespace ns = actionXml.getNamespace(); 867 Element prepareElement = actionXml.getChild("prepare", ns); 868 String prepareXML = ""; 869 if (prepareElement != null) { 870 if (prepareElement.getChildren().size() > 0) { 871 prepareXML = XmlUtils.prettyPrint(prepareElement).toString().trim(); 872 } 873 } 874 LauncherHelper.setupLauncherInfo(launcherJobConf, jobId, actionId, actionDir, recoveryId, actionConf, 875 prepareXML); 876 877 // Set the launcher Main Class 878 LauncherHelper.setupMainClass(launcherJobConf, getLauncherMain(launcherJobConf, actionXml)); 879 LauncherHelper.setupLauncherURIHandlerConf(launcherJobConf); 880 LauncherHelper.setupMaxOutputData(launcherJobConf, getMaxOutputData(actionConf)); 881 LauncherHelper.setupMaxExternalStatsSize(launcherJobConf, maxExternalStatsSize); 882 LauncherHelper.setupMaxFSGlob(launcherJobConf, maxFSGlobMax); 883 884 List<Element> list = actionXml.getChildren("arg", ns); 885 String[] args = new String[list.size()]; 886 for (int i = 0; i < list.size(); i++) { 887 args[i] = list.get(i).getTextTrim(); 888 } 889 LauncherHelper.setupMainArguments(launcherJobConf, args); 890 // backward compatibility flag - see OOZIE-2872 891 boolean nullArgsAllowed = ConfigurationService.getBoolean(LauncherAMUtils.CONF_OOZIE_NULL_ARGS_ALLOWED); 892 launcherJobConf.setBoolean(LauncherAMUtils.CONF_OOZIE_NULL_ARGS_ALLOWED, nullArgsAllowed); 893 894 // Make mapred.child.java.opts and mapreduce.map.java.opts equal, but give values from the latter priority; also append 895 // <java-opt> and <java-opts> and give those highest priority 896 StringBuilder opts = new StringBuilder(launcherJobConf.get(HADOOP_CHILD_JAVA_OPTS, "")); 897 if (launcherJobConf.get(HADOOP_MAP_JAVA_OPTS) != null) { 898 opts.append(" ").append(launcherJobConf.get(HADOOP_MAP_JAVA_OPTS)); 899 } 900 901 List<Element> javaopts = actionXml.getChildren("java-opt", ns); 902 903 // Either one or more <java-opt> element or one <java-opts> can be present since oozie-workflow-0.4 904 if (!javaopts.isEmpty()) { 905 for (Element opt : javaopts) { 906 opts.append(" ").append(opt.getTextTrim()); 907 } 908 } 909 else { 910 Element opt = actionXml.getChild("java-opts", ns); 911 if (opt != null) { 912 opts.append(" ").append(opt.getTextTrim()); 913 } 914 } 915 launcherJobConf.set(HADOOP_CHILD_JAVA_OPTS, opts.toString().trim()); 916 launcherJobConf.set(HADOOP_MAP_JAVA_OPTS, opts.toString().trim()); 917 918 injectLauncherTimelineServiceEnabled(launcherJobConf, actionConf); 919 920 // properties from action that are needed by the launcher (e.g. QUEUE NAME, ACLs) 921 // maybe we should add queue to the WF schema, below job-tracker 922 actionConfToLauncherConf(actionConf, launcherJobConf); 923 924 return launcherJobConf; 925 } 926 catch (Exception ex) { 927 throw convertException(ex); 928 } 929 } 930 931 @VisibleForTesting 932 protected static int getMaxOutputData(Configuration actionConf) { 933 String userMaxActionOutputLen = actionConf.get("oozie.action.max.output.data"); 934 if (userMaxActionOutputLen != null) { 935 Integer i = Ints.tryParse(userMaxActionOutputLen); 936 return i != null ? i : maxActionOutputLen; 937 } 938 return maxActionOutputLen; 939 } 940 941 protected void injectCallback(Context context, Configuration conf) { 942 String callback = context.getCallbackUrl(LauncherAMCallbackNotifier.OOZIE_LAUNCHER_CALLBACK_JOBSTATUS_TOKEN); 943 conf.set(LauncherAMCallbackNotifier.OOZIE_LAUNCHER_CALLBACK_URL, callback); 944 } 945 946 void injectActionCallback(Context context, Configuration actionConf) { 947 // action callback needs to be injected only for mapreduce actions. 948 } 949 950 void injectLauncherCallback(Context context, Configuration launcherConf) { 951 injectCallback(context, launcherConf); 952 } 953 954 private void actionConfToLauncherConf(Configuration actionConf, Configuration launcherConf) { 955 for (String name : SPECIAL_PROPERTIES) { 956 if (actionConf.get(name) != null && launcherConf.get("oozie.launcher." + name) == null) { 957 launcherConf.set(name, actionConf.get(name)); 958 } 959 } 960 } 961 962 public void submitLauncher(final FileSystem actionFs, final Context context, final WorkflowAction action) 963 throws ActionExecutorException { 964 YarnClient yarnClient = null; 965 try { 966 Path appPathRoot = new Path(context.getWorkflow().getAppPath()); 967 968 // app path could be a file 969 if (actionFs.isFile(appPathRoot)) { 970 appPathRoot = appPathRoot.getParent(); 971 } 972 973 Element actionXml = XmlUtils.parseXml(action.getConf()); 974 LOG.debug("ActionXML: {0}", action.getConf()); 975 976 // action job configuration 977 Configuration actionConf = loadHadoopDefaultResources(context, actionXml); 978 setupActionConf(actionConf, context, actionXml, appPathRoot); 979 addAppNameContext(context, action); 980 LOG.debug("Setting LibFilesArchives "); 981 setLibFilesArchives(context, actionXml, appPathRoot, actionConf); 982 983 String jobName = actionConf.get(HADOOP_JOB_NAME); 984 if (jobName == null || jobName.isEmpty()) { 985 jobName = getYarnApplicationName(context, action, "oozie:action"); 986 actionConf.set(HADOOP_JOB_NAME, jobName); 987 } 988 989 injectActionCallback(context, actionConf); 990 991 if(actionConf.get(ACL_MODIFY_JOB) == null || actionConf.get(ACL_MODIFY_JOB).trim().equals("")) { 992 // ONLY in the case where user has not given the 993 // modify-job ACL specifically 994 if (context.getWorkflow().getAcl() != null) { 995 // setting the group owning the Oozie job to allow anybody in that 996 // group to modify the jobs. 997 actionConf.set(ACL_MODIFY_JOB, context.getWorkflow().getAcl()); 998 } 999 } 1000 1001 Credentials credentials = new Credentials(); 1002 Configuration launcherConf = createLauncherConf(actionFs, context, action, actionXml, actionConf); 1003 yarnClient = createYarnClient(context, launcherConf); 1004 Map<String, CredentialsProperties> credentialsProperties = setCredentialPropertyToActionConf(context, 1005 action, actionConf); 1006 if (UserGroupInformation.isSecurityEnabled()) { 1007 addHadoopCredentialPropertiesToActionConf(credentialsProperties); 1008 } 1009 // Adding if action need to set more credential tokens 1010 Configuration credentialsConf = new Configuration(false); 1011 XConfiguration.copy(actionConf, credentialsConf); 1012 setCredentialTokens(credentials, credentialsConf, context, action, credentialsProperties); 1013 1014 // copy back new entries from credentialsConf 1015 for (Entry<String, String> entry : credentialsConf) { 1016 if (actionConf.get(entry.getKey()) == null) { 1017 actionConf.set(entry.getKey(), entry.getValue()); 1018 } 1019 } 1020 String consoleUrl; 1021 String launcherId = LauncherHelper.getRecoveryId(launcherConf, context.getActionDir(), context 1022 .getRecoveryId()); 1023 1024 removeHBaseSettingFromOozieDefaultResource(launcherConf); 1025 removeHBaseSettingFromOozieDefaultResource(actionConf); 1026 1027 1028 boolean alreadyRunning = launcherId != null; 1029 1030 // if user-retry is on, always submit new launcher 1031 boolean isUserRetry = ((WorkflowActionBean)action).isUserRetry(); 1032 LOG.debug("Creating yarnClient for action {0}", action.getId()); 1033 1034 if (alreadyRunning && !isUserRetry) { 1035 try { 1036 ApplicationId appId = ConverterUtils.toApplicationId(launcherId); 1037 ApplicationReport report = yarnClient.getApplicationReport(appId); 1038 consoleUrl = report.getTrackingUrl(); 1039 } catch (RemoteException e) { 1040 // caught when the application id does not exist 1041 LOG.error("Got RemoteException from YARN", e); 1042 String jobTracker = launcherConf.get(HADOOP_YARN_RM); 1043 throw new ActionExecutorException(ActionExecutorException.ErrorType.ERROR, "JA017", 1044 "unknown job [{0}@{1}], cannot recover", launcherId, jobTracker); 1045 } 1046 } 1047 else { 1048 YarnClientApplication newApp = yarnClient.createApplication(); 1049 ApplicationId appId = newApp.getNewApplicationResponse().getApplicationId(); 1050 ApplicationSubmissionContext appContext = 1051 createAppSubmissionContext(appId, launcherConf, context, actionConf, action, credentials, actionXml); 1052 yarnClient.submitApplication(appContext); 1053 1054 launcherId = appId.toString(); 1055 LOG.debug("After submission get the launcherId [{0}]", launcherId); 1056 ApplicationReport appReport = yarnClient.getApplicationReport(appId); 1057 consoleUrl = appReport.getTrackingUrl(); 1058 } 1059 1060 String jobTracker = launcherConf.get(HADOOP_YARN_RM); 1061 context.setStartData(launcherId, jobTracker, consoleUrl); 1062 } 1063 catch (Exception ex) { 1064 throw convertException(ex); 1065 } 1066 finally { 1067 if (yarnClient != null) { 1068 Closeables.closeQuietly(yarnClient); 1069 } 1070 } 1071 } 1072 1073 private String getYarnApplicationName(final Context context, final WorkflowAction action, final String prefix) { 1074 return XLog.format("{0}:T={1}:W={2}:A={3}:ID={4}", 1075 prefix, 1076 getType(), 1077 context.getWorkflow().getAppName(), 1078 action.getName(), 1079 context.getWorkflow().getId()); 1080 } 1081 1082 private void removeHBaseSettingFromOozieDefaultResource(final Configuration jobConf) { 1083 final String[] propertySources = jobConf.getPropertySources(HbaseCredentials.HBASE_USE_DYNAMIC_JARS); 1084 if (propertySources != null && propertySources.length > 0 && 1085 propertySources[0].contains(HbaseCredentials.OOZIE_HBASE_CLIENT_SITE_XML)) { 1086 jobConf.unset(HbaseCredentials.HBASE_USE_DYNAMIC_JARS); 1087 LOG.debug(String.format("Unset [%s] inserted from default Oozie resource XML [%s]", 1088 HbaseCredentials.HBASE_USE_DYNAMIC_JARS, HbaseCredentials.OOZIE_HBASE_CLIENT_SITE_XML)); 1089 } 1090 } 1091 1092 private void addAppNameContext(final Context context, final WorkflowAction action) { 1093 final String oozieActionName = getYarnApplicationName(context, action, "oozie:launcher"); 1094 context.setVar(OOZIE_ACTION_NAME, oozieActionName); 1095 } 1096 1097 protected String getAppName(Context context) { 1098 return context.getVar(OOZIE_ACTION_NAME); 1099 } 1100 1101 private void addHadoopCredentialPropertiesToActionConf(Map<String, CredentialsProperties> credentialsProperties) { 1102 LOG.info("Adding default credentials for action: hdfs, yarn and jhs"); 1103 addHadoopCredentialProperties(credentialsProperties, CredentialsProviderFactory.HDFS); 1104 addHadoopCredentialProperties(credentialsProperties, CredentialsProviderFactory.YARN); 1105 addHadoopCredentialProperties(credentialsProperties, CredentialsProviderFactory.JHS); 1106 } 1107 1108 private void addHadoopCredentialProperties(Map<String, CredentialsProperties> credentialsProperties, String type) { 1109 credentialsProperties.put(type, new CredentialsProperties(type, type)); 1110 } 1111 1112 private ApplicationSubmissionContext createAppSubmissionContext(final ApplicationId appId, 1113 final Configuration launcherJobConf, 1114 final Context actionContext, 1115 final Configuration actionConf, 1116 final WorkflowAction action, 1117 final Credentials credentials, 1118 final Element actionXml) 1119 throws IOException, HadoopAccessorException, URISyntaxException { 1120 1121 ApplicationSubmissionContext appContext = Records.newRecord(ApplicationSubmissionContext.class); 1122 1123 int priority = getPriority(launcherJobConf); 1124 setResources(launcherJobConf, appContext, priority); 1125 setQueue(launcherJobConf, appContext); 1126 1127 appContext.setApplicationId(appId); 1128 setApplicationName(actionContext, action, appContext); 1129 appContext.setApplicationType("Oozie Launcher"); 1130 setMaxAttempts(launcherJobConf, appContext); 1131 1132 ContainerLaunchContext amContainer = Records.newRecord(ContainerLaunchContext.class); 1133 YarnACLHandler yarnACL = new YarnACLHandler(launcherJobConf); 1134 yarnACL.setACLs(amContainer); 1135 1136 final String user = actionContext.getWorkflow().getUser(); 1137 setEnvironmentVariables(launcherJobConf, amContainer); 1138 // Set the resources to localize 1139 Map<String, LocalResource> localResources = new HashMap<String, LocalResource>(); 1140 ClientDistributedCacheManager.determineTimestampsAndCacheVisibilities(launcherJobConf); 1141 MRApps.setupDistributedCache(launcherJobConf, localResources); 1142 // Add the Launcher and Action configs as Resources 1143 HadoopAccessorService has = Services.get().get(HadoopAccessorService.class); 1144 launcherJobConf.set(LauncherAM.OOZIE_SUBMITTER_USER, user); 1145 LocalResource launcherJobConfLR = has.createLocalResourceForConfigurationFile(LauncherAM.LAUNCHER_JOB_CONF_XML, user, 1146 launcherJobConf, actionContext.getAppFileSystem().getUri(), actionContext.getActionDir()); 1147 localResources.put(LauncherAM.LAUNCHER_JOB_CONF_XML, launcherJobConfLR); 1148 LocalResource actionConfLR = has.createLocalResourceForConfigurationFile(LauncherAM.ACTION_CONF_XML, user, actionConf, 1149 actionContext.getAppFileSystem().getUri(), actionContext.getActionDir()); 1150 localResources.put(LauncherAM.ACTION_CONF_XML, actionConfLR); 1151 amContainer.setLocalResources(localResources); 1152 1153 1154 List<String> vargs = createCommand(launcherJobConf, actionContext); 1155 setJavaOpts(launcherJobConf, actionXml, vargs); 1156 vargs.add(LauncherAM.class.getCanonicalName()); 1157 vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + Path.SEPARATOR + ApplicationConstants.STDOUT); 1158 vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + Path.SEPARATOR + ApplicationConstants.STDERR); 1159 StringBuilder mergedCommand = new StringBuilder(); 1160 for (CharSequence str : vargs) { 1161 mergedCommand.append(str).append(" "); 1162 } 1163 1164 List<String> vargsFinal = ImmutableList.of(mergedCommand.toString()); 1165 LOG.debug("Command to launch container for ApplicationMaster is: {0}", mergedCommand); 1166 amContainer.setCommands(vargsFinal); 1167 appContext.setAMContainerSpec(amContainer); 1168 1169 // Set tokens 1170 if (credentials != null) { 1171 DataOutputBuffer dob = new DataOutputBuffer(); 1172 credentials.writeTokenStorageToStream(dob); 1173 amContainer.setTokens(ByteBuffer.wrap(dob.getData(), 0, dob.getLength())); 1174 } 1175 1176 appContext.setCancelTokensWhenComplete(true); 1177 1178 return appContext; 1179 } 1180 1181 private void setMaxAttempts(Configuration launcherJobConf, ApplicationSubmissionContext appContext) { 1182 int launcherMaxAttempts; 1183 final int defaultLauncherMaxAttempts = ConfigurationService.getInt(DEFAULT_LAUNCHER_MAX_ATTEMPTS); 1184 if (launcherJobConf.get(LauncherAM.OOZIE_LAUNCHER_MAX_ATTEMPTS) != null) { 1185 try { 1186 launcherMaxAttempts = launcherJobConf.getInt(LauncherAM.OOZIE_LAUNCHER_MAX_ATTEMPTS, 1187 defaultLauncherMaxAttempts); 1188 } catch (final NumberFormatException ignored) { 1189 launcherMaxAttempts = defaultLauncherMaxAttempts; 1190 } 1191 } else { 1192 LOG.warn("Invalid configuration value [{0}] defined for launcher max attempts count, using default [{1}].", 1193 launcherJobConf.get(LauncherAM.OOZIE_LAUNCHER_MAX_ATTEMPTS), 1194 defaultLauncherMaxAttempts); 1195 launcherMaxAttempts = defaultLauncherMaxAttempts; 1196 } 1197 1198 LOG.trace("Reading from configuration max attempts count of the Launcher AM. [launcherMaxAttempts={0}]", 1199 launcherMaxAttempts); 1200 1201 if (launcherMaxAttempts > 0) { 1202 LOG.trace("Setting max attempts of the Launcher AM. [launcherMaxAttempts={0}]", launcherMaxAttempts); 1203 appContext.setMaxAppAttempts(launcherMaxAttempts); 1204 } 1205 else { 1206 LOG.warn("Not setting max attempts of the Launcher AM, value is invalid. [launcherMaxAttempts={0}]", 1207 launcherMaxAttempts); 1208 } 1209 } 1210 1211 private List<String> createCommand(final Configuration launcherJobConf, final Context context) { 1212 final List<String> vargs = new ArrayList<String>(6); 1213 1214 String launcherLogLevel = launcherJobConf.get(LauncherAM.OOZIE_LAUNCHER_LOG_LEVEL_PROPERTY); 1215 if (Strings.isNullOrEmpty(launcherLogLevel)) { 1216 launcherLogLevel = "INFO"; 1217 } 1218 1219 vargs.add(Apps.crossPlatformify(ApplicationConstants.Environment.JAVA_HOME.toString()) 1220 + "/bin/java"); 1221 1222 vargs.add("-Dlog4j.configuration=container-log4j.properties"); 1223 vargs.add("-Dlog4j.debug=true"); 1224 vargs.add("-D" + YarnConfiguration.YARN_APP_CONTAINER_LOG_DIR + "=" + ApplicationConstants.LOG_DIR_EXPANSION_VAR); 1225 vargs.add("-D" + YarnConfiguration.YARN_APP_CONTAINER_LOG_SIZE + "=" + 1024 * 1024); 1226 vargs.add("-Dhadoop.root.logger=" + launcherLogLevel + ",CLA"); 1227 vargs.add("-Dhadoop.root.logfile=" + TaskLog.LogName.SYSLOG); 1228 vargs.add("-Dsubmitter.user=" + context.getWorkflow().getUser()); 1229 1230 return vargs; 1231 } 1232 1233 private void setJavaOpts(Configuration launcherJobConf, Element actionXml, List<String> vargs) { 1234 // Note: for backward compatibility reasons, we have to support the <java-opts> tag inside the <java> action 1235 // If both java/java-opt(s) and launcher/java-opts are defined, we pick java/java-opts 1236 // We also display a warning to let users know that they should migrate their workflow 1237 StringBuilder javaOpts = new StringBuilder(); 1238 boolean oldJavaOpts = handleJavaOpts(actionXml, javaOpts); 1239 if (oldJavaOpts) { 1240 vargs.add(javaOpts.toString()); 1241 } 1242 1243 final String oozieLauncherJavaOpts = launcherJobConf.get(LauncherAM.OOZIE_LAUNCHER_JAVAOPTS_PROPERTY); 1244 if (oozieLauncherJavaOpts != null) { 1245 if (oldJavaOpts) { 1246 LOG.warn("<java-opts> was defined inside the <launcher> tag -- ignored"); 1247 } else { 1248 vargs.add(oozieLauncherJavaOpts); 1249 } 1250 } 1251 } 1252 1253 private boolean handleJavaOpts(Element actionXml, StringBuilder javaOpts) { 1254 Namespace ns = actionXml.getNamespace(); 1255 boolean oldJavaOpts = false; 1256 @SuppressWarnings("unchecked") 1257 List<Element> javaopts = actionXml.getChildren("java-opt", ns); 1258 for (Element opt: javaopts) { 1259 javaOpts.append(" ").append(opt.getTextTrim()); 1260 oldJavaOpts = true; 1261 } 1262 Element opt = actionXml.getChild("java-opts", ns); 1263 if (opt != null) { 1264 javaOpts.append(" ").append(opt.getTextTrim()); 1265 oldJavaOpts = true; 1266 } 1267 1268 if (oldJavaOpts) { 1269 LOG.warn("Note: <java-opts> inside the action is used in the workflow. Please move <java-opts> tag under" 1270 + " the <launcher> element. See the documentation for details"); 1271 } 1272 return oldJavaOpts; 1273 } 1274 1275 private void setApplicationName(final Context context, 1276 final WorkflowAction action, 1277 final ApplicationSubmissionContext appContext) { 1278 final String jobName = getYarnApplicationName(context, action, "oozie:launcher"); 1279 appContext.setApplicationName(jobName); 1280 } 1281 1282 private void setEnvironmentVariables(Configuration launcherConf, ContainerLaunchContext amContainer) throws IOException { 1283 Map<String, String> env = new HashMap<>(); 1284 1285 final String oozieLauncherEnvProperty = launcherConf.get(LauncherAM.OOZIE_LAUNCHER_ENV_PROPERTY); 1286 if (oozieLauncherEnvProperty != null) { 1287 Map<String, String> environmentVars = extractEnvVarsFromOozieLauncherProps(oozieLauncherEnvProperty); 1288 env.putAll(environmentVars); 1289 } 1290 1291 // This adds the Hadoop jars to the classpath in the Launcher JVM 1292 ClasspathUtils.setupClasspath(env, launcherConf); 1293 1294 if (needToAddMapReduceToClassPath(launcherConf)) { 1295 ClasspathUtils.addMapReduceToClasspath(env, launcherConf); 1296 } 1297 1298 addActionSpecificEnvVars(env); 1299 amContainer.setEnvironment(ImmutableMap.copyOf(env)); 1300 } 1301 1302 private void setQueue(Configuration launcherJobConf, ApplicationSubmissionContext appContext) { 1303 String launcherQueueName; 1304 if (launcherJobConf.get(LauncherAM.OOZIE_LAUNCHER_QUEUE_PROPERTY) != null) { 1305 launcherQueueName = launcherJobConf.get(LauncherAM.OOZIE_LAUNCHER_QUEUE_PROPERTY); 1306 } else { 1307 launcherQueueName = Preconditions.checkNotNull( 1308 ConfigurationService.get(DEFAULT_LAUNCHER_QUEUE), "Default launcherQueueName is undefined"); 1309 } 1310 appContext.setQueue(launcherQueueName); 1311 } 1312 1313 private int getPriority(Configuration launcherJobConf) { 1314 int priority; 1315 if (launcherJobConf.get(LauncherAM.OOZIE_LAUNCHER_PRIORITY_PROPERTY) != null) { 1316 priority = launcherJobConf.getInt(LauncherAM.OOZIE_LAUNCHER_PRIORITY_PROPERTY, -1); 1317 } else { 1318 int defaultPriority = ConfigurationService.getInt(DEFAULT_LAUNCHER_PRIORITY); 1319 priority = defaultPriority; 1320 } 1321 return priority; 1322 } 1323 1324 private void setResources(Configuration launcherJobConf, ApplicationSubmissionContext appContext, int priority) { 1325 int memory; 1326 if (launcherJobConf.get(LauncherAM.OOZIE_LAUNCHER_MEMORY_MB_PROPERTY) != null) { 1327 memory = launcherJobConf.getInt(LauncherAM.OOZIE_LAUNCHER_MEMORY_MB_PROPERTY, -1); 1328 Preconditions.checkArgument(memory > 0, "Launcher memory is 0 or negative"); 1329 } else { 1330 int defaultMemory = ConfigurationService.getInt(DEFAULT_LAUNCHER_MEMORY_MB, -1); 1331 Preconditions.checkArgument(defaultMemory > 0, "Default launcher memory is 0 or negative"); 1332 memory = defaultMemory; 1333 } 1334 1335 int vcores; 1336 if (launcherJobConf.get(LauncherAM.OOZIE_LAUNCHER_VCORES_PROPERTY) != null) { 1337 vcores = launcherJobConf.getInt(LauncherAM.OOZIE_LAUNCHER_VCORES_PROPERTY, -1); 1338 Preconditions.checkArgument(vcores > 0, "Launcher vcores is 0 or negative"); 1339 } else { 1340 int defaultVcores = ConfigurationService.getInt(DEFAULT_LAUNCHER_VCORES); 1341 Preconditions.checkArgument(defaultVcores > 0, "Default launcher vcores is 0 or negative"); 1342 vcores = defaultVcores; 1343 } 1344 1345 Collection<String> locality = launcherJobConf.getStringCollection(MRJobConfig.AM_STRICT_LOCALITY); 1346 1347 List<ResourceRequest> resourceRequests = AMLocalityHelper.generateResourceRequests(memory, vcores, priority, locality); 1348 appContext.setAMContainerResourceRequests(resourceRequests); 1349 } 1350 1351 private Map<String, String> extractEnvVarsFromOozieLauncherProps(String oozieLauncherEnvProperty) { 1352 Map<String, String> envMap = new LinkedHashMap<>(); 1353 for (String envVar : StringUtils.split(oozieLauncherEnvProperty, File.pathSeparatorChar)) { 1354 String[] env = StringUtils.split(envVar, '='); 1355 Preconditions.checkArgument(env.length == 2, "Invalid launcher setting for environment variables: \"%s\". " + 1356 "<env> should contain a list of ENV_VAR_NAME=VALUE separated by the '%s' character. " + 1357 "Example on Unix: A=foo1:B=foo2", oozieLauncherEnvProperty, File.pathSeparator); 1358 envMap.put(env[0], env[1]); 1359 } 1360 return envMap; 1361 } 1362 1363 Map<String, CredentialsProperties> setCredentialPropertyToActionConf(final Context context, 1364 final WorkflowAction action, 1365 final Configuration actionConf) throws Exception { 1366 final Map<String, CredentialsProperties> credPropertiesMap = new HashMap<>(); 1367 if (context == null || action == null) { 1368 LOG.warn("context or action is null"); 1369 return credPropertiesMap; 1370 } 1371 final XConfiguration wfJobConf = getWorkflowConf(context); 1372 final boolean skipCredentials = actionConf.getBoolean(OOZIE_CREDENTIALS_SKIP, 1373 wfJobConf.getBoolean(OOZIE_CREDENTIALS_SKIP, ConfigurationService.getBoolean(OOZIE_CREDENTIALS_SKIP))); 1374 if (skipCredentials) { 1375 LOG.info("Skipping credentials (" + OOZIE_CREDENTIALS_SKIP + "=true)"); 1376 } else { 1377 credPropertiesMap.putAll(getActionCredentialsProperties(context, action)); 1378 if (credPropertiesMap.isEmpty()) { 1379 LOG.warn("No credential properties found for action : " + action.getId() + ", cred : " + action.getCred()); 1380 return credPropertiesMap; 1381 } 1382 for (final Entry<String, CredentialsProperties> entry : credPropertiesMap.entrySet()) { 1383 if (entry.getValue() != null) { 1384 final CredentialsProperties prop = entry.getValue(); 1385 LOG.debug("Credential Properties set for action : " + action.getId()); 1386 for (final Entry<String, String> propEntry : prop.getProperties().entrySet()) { 1387 final String key = propEntry.getKey(); 1388 final String value = propEntry.getValue(); 1389 actionConf.set(key, value); 1390 1391 LOG.debug("property : '" + key + "', value : '" + value + "'"); 1392 1393 } 1394 } 1395 } 1396 } 1397 return credPropertiesMap; 1398 } 1399 1400 protected void setCredentialTokens(Credentials credentials, Configuration jobconf, Context context, WorkflowAction action, 1401 Map<String, CredentialsProperties> credPropertiesMap) throws Exception { 1402 if (!isValidCredentialTokensPreconditions(context, action, credPropertiesMap)) { 1403 LOG.debug("Not obtaining delegation token(s) as preconditions do not hold."); 1404 return; 1405 } 1406 1407 setActionTokenProperties(jobconf); 1408 // Make sure we're logged into Kerberos; if not, or near expiration, it will relogin 1409 CredentialsProviderFactory.ensureKerberosLogin(); 1410 for (Entry<String, CredentialsProperties> entry : credPropertiesMap.entrySet()) { 1411 String credName = entry.getKey(); 1412 CredentialsProperties credProps = entry.getValue(); 1413 if (credProps != null) { 1414 CredentialsProvider tokenProvider = CredentialsProviderFactory.getInstance() 1415 .createCredentialsProvider(credProps.getType()); 1416 if (tokenProvider != null) { 1417 tokenProvider.updateCredentials(credentials, jobconf, credProps, context); 1418 LOG.debug("Retrieved Credential '" + credName + "' for action " + action.getId()); 1419 } else { 1420 LOG.debug("Credentials object is null for name= " + credName + ", type=" + credProps.getType()); 1421 throw new ActionExecutorException(ActionExecutorException.ErrorType.ERROR, "JA020", 1422 "Could not load credentials of type [{0}] with name [{1}]]; perhaps it was not defined" 1423 + " in oozie-site.xml?", credProps.getType(), credName); 1424 } 1425 } 1426 } 1427 } 1428 1429 private boolean isValidCredentialTokensPreconditions(final Context context, 1430 final WorkflowAction action, 1431 final Map<String, CredentialsProperties> credPropertiesMap) { 1432 return context != null && action != null && credPropertiesMap != null; 1433 } 1434 1435 /** 1436 * Subclasses may override this method in order to take additional actions required for obtaining credential token(s). 1437 * 1438 * @param jobconf workflow action configuration 1439 */ 1440 protected void setActionTokenProperties(final Configuration jobconf) { 1441 // nop 1442 } 1443 1444 protected HashMap<String, CredentialsProperties> getActionCredentialsProperties(Context context, 1445 WorkflowAction action) throws Exception { 1446 HashMap<String, CredentialsProperties> props = new HashMap<String, CredentialsProperties>(); 1447 if (context != null && action != null) { 1448 String credsInAction = action.getCred(); 1449 if (credsInAction != null) { 1450 LOG.debug("Get credential '" + credsInAction + "' properties for action : " + action.getId()); 1451 String[] credNames = credsInAction.split(","); 1452 for (String credName : credNames) { 1453 CredentialsProperties credProps = getCredProperties(context, credName); 1454 props.put(credName, credProps); 1455 } 1456 } 1457 } 1458 else { 1459 LOG.warn("context or action is null"); 1460 } 1461 return props; 1462 } 1463 1464 @SuppressWarnings("unchecked") 1465 protected CredentialsProperties getCredProperties(Context context, String credName) 1466 throws Exception { 1467 CredentialsProperties credProp = null; 1468 String workflowXml = ((WorkflowJobBean) context.getWorkflow()).getWorkflowInstance().getApp().getDefinition(); 1469 XConfiguration wfjobConf = getWorkflowConf(context); 1470 Element elementJob = XmlUtils.parseXml(workflowXml); 1471 Element credentials = elementJob.getChild("credentials", elementJob.getNamespace()); 1472 if (credentials != null) { 1473 for (Element credential : (List<Element>) credentials.getChildren("credential", credentials.getNamespace())) { 1474 String name = credential.getAttributeValue("name"); 1475 String type = credential.getAttributeValue("type"); 1476 LOG.debug("getCredProperties: Name: " + name + ", Type: " + type); 1477 if (name.equalsIgnoreCase(credName)) { 1478 credProp = new CredentialsProperties(name, type); 1479 for (Element property : (List<Element>) credential.getChildren("property", 1480 credential.getNamespace())) { 1481 String propertyName = property.getChildText("name", property.getNamespace()); 1482 String propertyValue = property.getChildText("value", property.getNamespace()); 1483 ELEvaluator eval = new ELEvaluator(); 1484 for (Map.Entry<String, String> entry : wfjobConf) { 1485 eval.setVariable(entry.getKey(), entry.getValue().trim()); 1486 } 1487 propertyName = eval.evaluate(propertyName, String.class); 1488 propertyValue = eval.evaluate(propertyValue, String.class); 1489 1490 credProp.getProperties().put(propertyName, propertyValue); 1491 LOG.debug("getCredProperties: Properties name :'" + propertyName + "', Value : '" 1492 + propertyValue + "'"); 1493 } 1494 } 1495 } 1496 if (credProp == null && credName != null) { 1497 throw new ActionExecutorException(ActionExecutorException.ErrorType.ERROR, "JA021", 1498 "Could not load credentials with name [{0}]].", credName); 1499 } 1500 } else { 1501 LOG.debug("credentials is null for the action"); 1502 } 1503 return credProp; 1504 } 1505 1506 @Override 1507 public void start(Context context, WorkflowAction action) throws ActionExecutorException { 1508 LogUtils.setLogInfo(action); 1509 try { 1510 LOG.info("Starting action. Getting Action File System"); 1511 FileSystem actionFs = context.getAppFileSystem(); 1512 LOG.debug("Preparing action Dir through copying " + context.getActionDir()); 1513 prepareActionDir(actionFs, context); 1514 LOG.debug("Action Dir is ready. Submitting the action "); 1515 submitLauncher(actionFs, context, action); 1516 LOG.debug("Action submit completed. Performing check "); 1517 check(context, action); 1518 LOG.debug("Action check is done after submission"); 1519 } 1520 catch (Exception ex) { 1521 throw convertException(ex); 1522 } 1523 } 1524 1525 @Override 1526 public void end(Context context, WorkflowAction action) throws ActionExecutorException { 1527 LOG.info("Action ended with external status [{0}]", action.getExternalStatus()); 1528 try { 1529 String externalStatus = action.getExternalStatus(); 1530 WorkflowAction.Status status = externalStatus.equals(SUCCEEDED) ? WorkflowAction.Status.OK 1531 : WorkflowAction.Status.ERROR; 1532 context.setEndData(status, getActionSignal(status)); 1533 } 1534 catch (Exception ex) { 1535 throw convertException(ex); 1536 } 1537 finally { 1538 try { 1539 FileSystem actionFs = context.getAppFileSystem(); 1540 cleanUpActionDir(actionFs, context); 1541 } 1542 catch (Exception ex) { 1543 throw convertException(ex); 1544 } 1545 } 1546 } 1547 1548 /** 1549 * Create job client object 1550 * 1551 * @param context 1552 * @param jobConf 1553 * @return JobClient 1554 * @throws HadoopAccessorException 1555 */ 1556 protected JobClient createJobClient(Context context, Configuration jobConf) throws HadoopAccessorException { 1557 String user = context.getWorkflow().getUser(); 1558 return Services.get().get(HadoopAccessorService.class).createJobClient(user, jobConf); 1559 } 1560 1561 /** 1562 * Create yarn client object 1563 * 1564 * @param context 1565 * @param jobConf 1566 * @return YarnClient 1567 * @throws HadoopAccessorException 1568 */ 1569 protected YarnClient createYarnClient(Context context, Configuration jobConf) throws HadoopAccessorException { 1570 String user = context.getWorkflow().getUser(); 1571 return Services.get().get(HadoopAccessorService.class).createYarnClient(user, jobConf); 1572 } 1573 1574 /** 1575 * Useful for overriding in actions that do subsequent job runs 1576 * such as the MapReduce Action, where the launcher job is not the 1577 * actual job that then gets monitored. 1578 * @param action 1579 * @return external ID. 1580 */ 1581 protected String getActualExternalId(WorkflowAction action) { 1582 return action.getExternalId(); 1583 } 1584 1585 /** 1586 * If returns true, it means that we have to add Hadoop MR jars to the classpath. 1587 * Subclasses should override this method if necessary. By default we don't add 1588 * MR jars to the classpath. 1589 * 1590 * <p>Configuration properties are read either from {@code launcherConf}, or, if not present, falling back to 1591 * {@link ConfigurationService#getBoolean(Configuration, String)}. 1592 * 1593 * @return false by default 1594 * @param launcherConf the launcher {@link Configuration} that is used on first lookup 1595 */ 1596 private boolean needToAddMapReduceToClassPath(final Configuration launcherConf) { 1597 LOG.debug("Calculating whether to add MapReduce JARs to classpath. [type={0};this={1}]", getType(), this); 1598 1599 final boolean defaultValue = ConfigurationService.getBooleanOrDefault( 1600 launcherConf, 1601 OOZIE_LAUNCHER_ADD_MAPREDUCE_TO_CLASSPATH_PROPERTY, 1602 false); 1603 LOG.debug("Default value for [{0}] is [{1}]", OOZIE_LAUNCHER_ADD_MAPREDUCE_TO_CLASSPATH_PROPERTY, defaultValue); 1604 1605 final String configurationKey = OOZIE_LAUNCHER_ADD_MAPREDUCE_TO_CLASSPATH_PROPERTY + "." + getType(); 1606 final boolean configuredValue = ConfigurationService.getBooleanOrDefault(launcherConf, configurationKey, defaultValue); 1607 LOG.debug("Configured value for [{0}] is [{1}]", configurationKey, configuredValue); 1608 1609 return configuredValue; 1610 } 1611 1612 /** 1613 * Adds action-specific environment variables. Default implementation is no-op. 1614 * Subclasses should override this method if necessary. 1615 * @param env action specific environment variables stored as Map of key and value. 1616 */ 1617 protected void addActionSpecificEnvVars(Map<String, String> env) { 1618 // nop 1619 } 1620 1621 @Override 1622 public void check(Context context, WorkflowAction action) throws ActionExecutorException { 1623 boolean fallback = false; 1624 LOG = XLog.resetPrefix(LOG); 1625 LogUtils.setLogInfo(action); 1626 YarnClient yarnClient = null; 1627 try { 1628 Element actionXml = XmlUtils.parseXml(action.getConf()); 1629 Configuration jobConf = createBaseHadoopConf(context, actionXml); 1630 FileSystem actionFs = context.getAppFileSystem(); 1631 yarnClient = createYarnClient(context, jobConf); 1632 FinalApplicationStatus appStatus = null; 1633 try { 1634 final String effectiveApplicationId = findYarnApplicationId(context, action); 1635 final ApplicationId applicationId = ConverterUtils.toApplicationId(effectiveApplicationId); 1636 final ApplicationReport appReport = yarnClient.getApplicationReport(applicationId); 1637 final YarnApplicationState appState = appReport.getYarnApplicationState(); 1638 if (appState == YarnApplicationState.FAILED || appState == YarnApplicationState.FINISHED 1639 || appState == YarnApplicationState.KILLED) { 1640 appStatus = appReport.getFinalApplicationStatus(); 1641 } 1642 } catch (final ActionExecutorException aae) { 1643 LOG.warn("Foreseen Exception occurred while action execution; rethrowing ", aae); 1644 throw aae; 1645 } catch (final Exception ye) { 1646 LOG.warn("Exception occurred while checking Launcher AM status; will try checking action data file instead ", ye); 1647 // Fallback to action data file if we can't find the Launcher AM (maybe it got purged) 1648 fallback = true; 1649 } 1650 if (appStatus != null || fallback) { 1651 Path actionDir = context.getActionDir(); 1652 // load sequence file into object 1653 Map<String, String> actionData = LauncherHelper.getActionData(actionFs, actionDir, jobConf); 1654 if (fallback) { 1655 String finalStatus = actionData.get(LauncherAM.ACTION_DATA_FINAL_STATUS); 1656 if (finalStatus != null) { 1657 appStatus = FinalApplicationStatus.valueOf(finalStatus); 1658 } else { 1659 context.setExecutionData(FAILED, null); 1660 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "JA017", 1661 "Unknown hadoop job [{0}] associated with action [{1}] and couldn't determine status from" + 1662 " action data. Failing this action!", action.getExternalId(), action.getId()); 1663 } 1664 } 1665 1666 String externalID = actionData.get(LauncherAM.ACTION_DATA_NEW_ID); // MapReduce was launched 1667 if (externalID != null) { 1668 context.setExternalChildIDs(externalID); 1669 LOG.info(XLog.STD, "Hadoop Job was launched : [{0}]", externalID); 1670 } 1671 1672 // Multiple child IDs - Pig or Hive action 1673 String externalIDs = actionData.get(LauncherAM.ACTION_DATA_EXTERNAL_CHILD_IDS); 1674 if (externalIDs != null) { 1675 context.setExternalChildIDs(externalIDs); 1676 LOG.info(XLog.STD, "External Child IDs : [{0}]", externalIDs); 1677 1678 } 1679 1680 LOG.info(XLog.STD, "action completed, external ID [{0}]", action.getExternalId()); 1681 context.setExecutionData(appStatus.toString(), null); 1682 if (appStatus == FinalApplicationStatus.SUCCEEDED) { 1683 if (getCaptureOutput(action) && LauncherHelper.hasOutputData(actionData)) { 1684 context.setExecutionData(SUCCEEDED, PropertiesUtils.stringToProperties(actionData 1685 .get(LauncherAM.ACTION_DATA_OUTPUT_PROPS))); 1686 LOG.info(XLog.STD, "action produced output"); 1687 } 1688 else { 1689 context.setExecutionData(SUCCEEDED, null); 1690 } 1691 if (LauncherHelper.hasStatsData(actionData)) { 1692 context.setExecutionStats(actionData.get(LauncherAM.ACTION_DATA_STATS)); 1693 LOG.info(XLog.STD, "action produced stats"); 1694 } 1695 getActionData(actionFs, action, context); 1696 } 1697 else { 1698 String errorReason; 1699 if (actionData.containsKey(LauncherAM.ACTION_DATA_ERROR_PROPS)) { 1700 Properties props = PropertiesUtils.stringToProperties(actionData 1701 .get(LauncherAM.ACTION_DATA_ERROR_PROPS)); 1702 String errorCode = props.getProperty("error.code"); 1703 if ("0".equals(errorCode)) { 1704 errorCode = "JA018"; 1705 } 1706 if ("-1".equals(errorCode)) { 1707 errorCode = "JA019"; 1708 } 1709 errorReason = props.getProperty("error.reason"); 1710 LOG.warn("Launcher ERROR, reason: {0}", errorReason); 1711 String exMsg = props.getProperty("exception.message"); 1712 String errorInfo = (exMsg != null) ? exMsg : errorReason; 1713 context.setErrorInfo(errorCode, errorInfo); 1714 String exStackTrace = props.getProperty("exception.stacktrace"); 1715 if (exMsg != null) { 1716 LOG.warn("Launcher exception: {0}{E}{1}", exMsg, exStackTrace); 1717 } 1718 } 1719 else { 1720 errorReason = XLog.format("Launcher AM died, check Hadoop LOG for job [{0}:{1}]", action 1721 .getTrackerUri(), action.getExternalId()); 1722 LOG.warn(errorReason); 1723 } 1724 context.setExecutionData(FAILED_KILLED, null); 1725 } 1726 } 1727 else { 1728 context.setExternalStatus(YarnApplicationState.RUNNING.toString()); 1729 LOG.info(XLog.STD, "checking action, hadoop job ID [{0}] status [RUNNING]", 1730 action.getExternalId()); 1731 } 1732 } 1733 catch (Exception ex) { 1734 LOG.warn("Exception in check(). Message[{0}]", ex.getMessage(), ex); 1735 throw convertException(ex); 1736 } 1737 finally { 1738 if (yarnClient != null) { 1739 IOUtils.closeQuietly(yarnClient); 1740 } 1741 } 1742 } 1743 1744 /** 1745 * For every {@link JavaActionExecutor} that is not {@link MapReduceActionExecutor}, the effective YARN application ID of the 1746 * action is the one where {@link LauncherAM} is run, hence this default implementation. 1747 * @param context the execution context 1748 * @param action the workflow action 1749 * @return a {@code String} that depicts the application ID of the launcher ApplicationMaster of this action 1750 * @throws ActionExecutorException 1751 */ 1752 protected String findYarnApplicationId(final Context context, final WorkflowAction action) 1753 throws ActionExecutorException { 1754 return action.getExternalId(); 1755 } 1756 1757 /** 1758 * Get the output data of an action. Subclasses should override this method 1759 * to get action specific output data. 1760 * @param actionFs the FileSystem object 1761 * @param action the Workflow action 1762 * @param context executor context 1763 * @throws org.apache.oozie.service.HadoopAccessorException 1764 * @throws org.jdom.JDOMException 1765 * @throws java.io.IOException 1766 * @throws java.net.URISyntaxException 1767 * 1768 */ 1769 protected void getActionData(FileSystem actionFs, WorkflowAction action, Context context) 1770 throws HadoopAccessorException, JDOMException, IOException, URISyntaxException { 1771 } 1772 1773 protected boolean getCaptureOutput(WorkflowAction action) throws JDOMException { 1774 Element eConf = XmlUtils.parseXml(action.getConf()); 1775 Namespace ns = eConf.getNamespace(); 1776 Element captureOutput = eConf.getChild("capture-output", ns); 1777 return captureOutput != null; 1778 } 1779 1780 @Override 1781 public void kill(Context context, WorkflowAction action) throws ActionExecutorException { 1782 YarnClient yarnClient = null; 1783 try { 1784 Element actionXml = XmlUtils.parseXml(action.getConf()); 1785 final Configuration jobConf = createBaseHadoopConf(context, actionXml); 1786 String launcherTag = getActionYarnTag(context, action); 1787 jobConf.set(LauncherMain.CHILD_MAPREDUCE_JOB_TAGS, LauncherHelper.getTag(launcherTag)); 1788 yarnClient = createYarnClient(context, jobConf); 1789 if(action.getExternalId() != null) { 1790 try { 1791 LOG.info("Killing action {0}'s external application {1}", action.getId(), action.getExternalId()); 1792 yarnClient.killApplication(ConverterUtils.toApplicationId(action.getExternalId())); 1793 } catch (Exception e) { 1794 LOG.warn("Could not kill {0}", action.getExternalId(), e); 1795 } 1796 } 1797 String externalChildIDs = action.getExternalChildIDs(); 1798 if(externalChildIDs != null) { 1799 for(String childId : externalChildIDs.split(",")) { 1800 try { 1801 LOG.info("Killing action {0}'s external child application {1}", action.getId(), childId); 1802 yarnClient.killApplication(ConverterUtils.toApplicationId(childId.trim())); 1803 } catch (Exception e) { 1804 LOG.warn("Could not kill external child of {0}, {1}", action.getExternalId(), 1805 childId, e); 1806 } 1807 } 1808 } 1809 for(ApplicationId id : LauncherMain.getChildYarnJobs(jobConf, ApplicationsRequestScope.ALL, 1810 action.getStartTime().getTime())){ 1811 try { 1812 LOG.info("Killing action {0}'s external child application {1} based on tags", 1813 action.getId(), id.toString()); 1814 yarnClient.killApplication(id); 1815 } catch (Exception e) { 1816 LOG.warn("Could not kill child of {0}, {1}", action.getExternalId(), id, e); 1817 } 1818 } 1819 1820 context.setExternalStatus(KILLED); 1821 context.setExecutionData(KILLED, null); 1822 } catch (Exception ex) { 1823 LOG.error("Error when killing YARN application", ex); 1824 throw convertException(ex); 1825 } finally { 1826 try { 1827 FileSystem actionFs = context.getAppFileSystem(); 1828 cleanUpActionDir(actionFs, context); 1829 Closeables.closeQuietly(yarnClient); 1830 } catch (Exception ex) { 1831 LOG.error("Error when cleaning up action dir", ex); 1832 throw convertException(ex); 1833 } 1834 } 1835 } 1836 1837 protected String getActionYarnTag(Context context, WorkflowAction action) { 1838 return LauncherHelper.getActionYarnTag(context.getProtoActionConf(), context.getWorkflow().getParentId(), action); 1839 } 1840 1841 private static Set<String> FINAL_STATUS = new HashSet<String>(); 1842 1843 static { 1844 FINAL_STATUS.add(SUCCEEDED); 1845 FINAL_STATUS.add(KILLED); 1846 FINAL_STATUS.add(FAILED); 1847 FINAL_STATUS.add(FAILED_KILLED); 1848 } 1849 1850 @Override 1851 public boolean isCompleted(String externalStatus) { 1852 return FINAL_STATUS.contains(externalStatus); 1853 } 1854 1855 1856 /** 1857 * Return the sharelib names for the action. 1858 * See {@link SharelibResolver} for details. 1859 * 1860 * @param context executor context. 1861 * @param actionXml the action xml. 1862 * @param conf action configuration. 1863 * @return the action sharelib names. 1864 */ 1865 protected String[] getShareLibNames(final Context context, final Element actionXml, Configuration conf) { 1866 final String sharelibFromConfigurationProperty = ACTION_SHARELIB_FOR + getType(); 1867 try { 1868 final String defaultShareLibName = getDefaultShareLibName(actionXml); 1869 final Configuration oozieServerConfiguration = Services.get().get(ConfigurationService.class).getConf(); 1870 final XConfiguration workflowConfiguration = getWorkflowConf(context); 1871 return new SharelibResolver(sharelibFromConfigurationProperty, conf, workflowConfiguration, 1872 oozieServerConfiguration, defaultShareLibName).resolve(); 1873 } catch (IOException ex) { 1874 throw new RuntimeException("Can't get workflow configuration: " + ex.toString(), ex); 1875 } 1876 } 1877 1878 1879 /** 1880 * Returns the default sharelib name for the action if any. 1881 * 1882 * @param actionXml the action XML fragment. 1883 * @return the sharelib name for the action, <code>NULL</code> if none. 1884 */ 1885 protected String getDefaultShareLibName(Element actionXml) { 1886 return null; 1887 } 1888 1889 public String[] getShareLibFilesForActionConf() { 1890 return null; 1891 } 1892 1893 /** 1894 * Sets some data for the action on completion 1895 * 1896 * @param context executor context 1897 * @param actionFs the FileSystem object 1898 * @throws java.io.IOException 1899 * @throws org.apache.oozie.service.HadoopAccessorException 1900 * @throws java.net.URISyntaxException 1901 */ 1902 protected void setActionCompletionData(Context context, FileSystem actionFs) throws IOException, 1903 HadoopAccessorException, URISyntaxException { 1904 } 1905 1906 private void injectJobInfo(Configuration launcherJobConf, Configuration actionConf, Context context, WorkflowAction action) { 1907 if (OozieJobInfo.isJobInfoEnabled()) { 1908 try { 1909 OozieJobInfo jobInfo = new OozieJobInfo(actionConf, context, action); 1910 String jobInfoStr = jobInfo.getJobInfo(); 1911 launcherJobConf.set(OozieJobInfo.JOB_INFO_KEY, jobInfoStr + "launcher=true"); 1912 actionConf.set(OozieJobInfo.JOB_INFO_KEY, jobInfoStr + "launcher=false"); 1913 } 1914 catch (Exception e) { 1915 // Just job info, should not impact the execution. 1916 LOG.error("Error while populating job info", e); 1917 } 1918 } 1919 } 1920 1921 @Override 1922 public boolean requiresNameNodeJobTracker() { 1923 return true; 1924 } 1925 1926 @Override 1927 public boolean supportsConfigurationJobXML() { 1928 return true; 1929 } 1930 1931 private XConfiguration getWorkflowConf(Context context) throws IOException { 1932 if (workflowConf == null) { 1933 workflowConf = new XConfiguration(new StringReader(context.getWorkflow().getConf())); 1934 } 1935 return workflowConf; 1936 1937 } 1938 1939 private String getActionTypeLauncherPrefix() { 1940 return "oozie.action." + getType() + ".launcher."; 1941 } 1942}