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.io.Closeables; 025import com.google.common.primitives.Ints; 026 027import java.io.File; 028import java.io.FileNotFoundException; 029import java.io.IOException; 030import java.io.StringReader; 031import java.net.ConnectException; 032import java.net.URI; 033import java.net.URISyntaxException; 034import java.net.UnknownHostException; 035import java.nio.ByteBuffer; 036import java.text.MessageFormat; 037import java.util.ArrayList; 038import java.util.Arrays; 039import java.util.Collection; 040import java.util.HashMap; 041import java.util.HashSet; 042import java.util.Iterator; 043import java.util.LinkedHashMap; 044import java.util.List; 045import java.util.Map; 046import java.util.Map.Entry; 047 048import org.apache.commons.io.IOUtils; 049import org.apache.hadoop.conf.Configuration; 050import org.apache.hadoop.filecache.DistributedCache; 051import org.apache.hadoop.fs.FileStatus; 052import org.apache.hadoop.fs.FileSystem; 053import org.apache.hadoop.fs.Path; 054import org.apache.hadoop.io.DataOutputBuffer; 055import org.apache.hadoop.ipc.RemoteException; 056import org.apache.hadoop.mapred.JobClient; 057import org.apache.hadoop.mapred.TaskLog; 058import org.apache.hadoop.mapreduce.MRJobConfig; 059import org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager; 060import org.apache.hadoop.mapreduce.v2.util.MRApps; 061import org.apache.hadoop.security.AccessControlException; 062import org.apache.hadoop.security.Credentials; 063import org.apache.hadoop.security.UserGroupInformation; 064import org.apache.hadoop.util.DiskChecker; 065import org.apache.hadoop.util.StringUtils; 066import org.apache.hadoop.yarn.api.ApplicationConstants; 067import org.apache.hadoop.yarn.api.protocolrecords.ApplicationsRequestScope; 068import org.apache.hadoop.yarn.api.records.ApplicationId; 069import org.apache.hadoop.yarn.api.records.ApplicationReport; 070import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; 071import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; 072import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; 073import org.apache.hadoop.yarn.api.records.LocalResource; 074import org.apache.hadoop.yarn.api.records.ResourceRequest; 075import org.apache.hadoop.yarn.api.records.YarnApplicationState; 076import org.apache.hadoop.yarn.client.api.YarnClient; 077import org.apache.hadoop.yarn.client.api.YarnClientApplication; 078import org.apache.hadoop.yarn.conf.YarnConfiguration; 079import org.apache.hadoop.yarn.util.Apps; 080import org.apache.hadoop.yarn.util.ConverterUtils; 081import org.apache.hadoop.yarn.util.Records; 082import org.apache.oozie.WorkflowActionBean; 083import org.apache.oozie.WorkflowJobBean; 084import org.apache.oozie.action.ActionExecutor; 085import org.apache.oozie.action.ActionExecutorException; 086import org.apache.oozie.client.OozieClient; 087import org.apache.oozie.client.WorkflowAction; 088import org.apache.oozie.command.coord.CoordActionStartXCommand; 089import org.apache.oozie.command.wf.WorkflowXCommand; 090import org.apache.oozie.service.ConfigurationService; 091import org.apache.oozie.service.HadoopAccessorException; 092import org.apache.oozie.service.HadoopAccessorService; 093import org.apache.oozie.service.Services; 094import org.apache.oozie.service.ShareLibService; 095import org.apache.oozie.service.URIHandlerService; 096import org.apache.oozie.service.WorkflowAppService; 097import org.apache.oozie.util.ClasspathUtils; 098import org.apache.oozie.util.ELEvaluationException; 099import org.apache.oozie.util.ELEvaluator; 100import org.apache.oozie.util.FSUtils; 101import org.apache.oozie.util.JobUtils; 102import org.apache.oozie.util.LogUtils; 103import org.apache.oozie.util.PropertiesUtils; 104import org.apache.oozie.util.XConfiguration; 105import org.apache.oozie.util.XLog; 106import org.apache.oozie.util.XmlUtils; 107import org.jdom.Element; 108import org.jdom.JDOMException; 109import org.jdom.Namespace; 110 111import java.util.Objects; 112import java.util.Properties; 113import java.util.Set; 114 115import com.google.common.base.Preconditions; 116import com.google.common.collect.ImmutableMap; 117 118public class JavaActionExecutor extends ActionExecutor { 119 public static final String RUNNING = "RUNNING"; 120 public static final String SUCCEEDED = "SUCCEEDED"; 121 public static final String KILLED = "KILLED"; 122 public static final String FAILED = "FAILED"; 123 public static final String FAILED_KILLED = "FAILED/KILLED"; 124 public static final String HADOOP_YARN_RM = "yarn.resourcemanager.address"; 125 public static final String HADOOP_NAME_NODE = "fs.default.name"; 126 public static final String OOZIE_COMMON_LIBDIR = "oozie"; 127 128 public static final String DEFAULT_LAUNCHER_VCORES = "oozie.launcher.default.vcores"; 129 public static final String DEFAULT_LAUNCHER_MEMORY_MB = "oozie.launcher.default.memory.mb"; 130 public static final String DEFAULT_LAUNCHER_PRIORITY = "oozie.launcher.default.priority"; 131 public static final String DEFAULT_LAUNCHER_QUEUE = "oozie.launcher.default.queue"; 132 public static final String DEFAULT_LAUNCHER_MAX_ATTEMPS = "oozie.launcher.default.max.attempts"; 133 public static final String LAUNCER_MODIFY_ACL = "oozie.launcher.modify.acl"; 134 public static final String LAUNCER_VIEW_ACL = "oozie.launcher.view.acl"; 135 136 public static final String MAPREDUCE_TO_CLASSPATH = "mapreduce.needed.for"; 137 public static final String OOZIE_LAUNCHER_ADD_MAPREDUCE_TO_CLASSPATH_PROPERTY = ActionExecutor.CONF_PREFIX 138 + MAPREDUCE_TO_CLASSPATH; 139 140 public static final String MAX_EXTERNAL_STATS_SIZE = "oozie.external.stats.max.size"; 141 public static final String ACL_VIEW_JOB = "mapreduce.job.acl-view-job"; 142 public static final String ACL_MODIFY_JOB = "mapreduce.job.acl-modify-job"; 143 public static final String HADOOP_YARN_TIMELINE_SERVICE_ENABLED = "yarn.timeline-service.enabled"; 144 public static final String HADOOP_YARN_UBER_MODE = "mapreduce.job.ubertask.enable"; 145 public static final String OOZIE_ACTION_LAUNCHER_PREFIX = ActionExecutor.CONF_PREFIX + "launcher."; 146 public static final String HADOOP_YARN_KILL_CHILD_JOBS_ON_AMRESTART = 147 OOZIE_ACTION_LAUNCHER_PREFIX + "am.restart.kill.childjobs"; 148 public static final String HADOOP_MAP_MEMORY_MB = "mapreduce.map.memory.mb"; 149 public static final String HADOOP_CHILD_JAVA_OPTS = "mapred.child.java.opts"; 150 public static final String HADOOP_MAP_JAVA_OPTS = "mapreduce.map.java.opts"; 151 public static final String HADOOP_REDUCE_JAVA_OPTS = "mapreduce.reduce.java.opts"; 152 public static final String HADOOP_CHILD_JAVA_ENV = "mapred.child.env"; 153 public static final String HADOOP_MAP_JAVA_ENV = "mapreduce.map.env"; 154 public static final String HADOOP_JOB_CLASSLOADER = "mapreduce.job.classloader"; 155 public static final String HADOOP_USER_CLASSPATH_FIRST = "mapreduce.user.classpath.first"; 156 public static final String OOZIE_CREDENTIALS_SKIP = "oozie.credentials.skip"; 157 public static final String YARN_AM_RESOURCE_MB = "yarn.app.mapreduce.am.resource.mb"; 158 public static final String YARN_AM_COMMAND_OPTS = "yarn.app.mapreduce.am.command-opts"; 159 public static final String YARN_AM_ENV = "yarn.app.mapreduce.am.env"; 160 public static final int YARN_MEMORY_MB_MIN = 512; 161 162 private static final String JAVA_MAIN_CLASS_NAME = "org.apache.oozie.action.hadoop.JavaMain"; 163 private static final String HADOOP_JOB_NAME = "mapred.job.name"; 164 private static final Set<String> DISALLOWED_PROPERTIES = new HashSet<String>(); 165 private static final String OOZIE_ACTION_NAME = "oozie.action.name"; 166 private final static String ACTION_SHARELIB_FOR = "oozie.action.sharelib.for."; 167 168 private static int maxActionOutputLen; 169 private static int maxExternalStatsSize; 170 private static int maxFSGlobMax; 171 172 protected static final String HADOOP_USER = "user.name"; 173 174 protected XLog LOG = XLog.getLog(getClass()); 175 private static final String JAVA_TMP_DIR_SETTINGS = "-Djava.io.tmpdir="; 176 177 public XConfiguration workflowConf = null; 178 179 static { 180 DISALLOWED_PROPERTIES.add(HADOOP_USER); 181 DISALLOWED_PROPERTIES.add(HADOOP_NAME_NODE); 182 DISALLOWED_PROPERTIES.add(HADOOP_YARN_RM); 183 } 184 185 public JavaActionExecutor() { 186 this("java"); 187 } 188 189 protected JavaActionExecutor(String type) { 190 super(type); 191 } 192 193 public static List<Class<?>> getCommonLauncherClasses() { 194 List<Class<?>> classes = new ArrayList<Class<?>>(); 195 classes.add(LauncherMain.class); 196 classes.addAll(Services.get().get(URIHandlerService.class).getClassesForLauncher()); 197 classes.add(LauncherAM.class); 198 classes.add(LauncherAMCallbackNotifier.class); 199 return classes; 200 } 201 202 public List<Class<?>> getLauncherClasses() { 203 List<Class<?>> classes = new ArrayList<Class<?>>(); 204 try { 205 classes.add(Class.forName(JAVA_MAIN_CLASS_NAME)); 206 } 207 catch (ClassNotFoundException e) { 208 throw new RuntimeException("Class not found", e); 209 } 210 return classes; 211 } 212 213 @Override 214 public void initActionType() { 215 super.initActionType(); 216 maxActionOutputLen = ConfigurationService.getInt(LauncherAM.CONF_OOZIE_ACTION_MAX_OUTPUT_DATA); 217 //Get the limit for the maximum allowed size of action stats 218 maxExternalStatsSize = ConfigurationService.getInt(JavaActionExecutor.MAX_EXTERNAL_STATS_SIZE); 219 maxExternalStatsSize = (maxExternalStatsSize == -1) ? Integer.MAX_VALUE : maxExternalStatsSize; 220 //Get the limit for the maximum number of globbed files/dirs for FS operation 221 maxFSGlobMax = ConfigurationService.getInt(LauncherAMUtils.CONF_OOZIE_ACTION_FS_GLOB_MAX); 222 223 registerError(UnknownHostException.class.getName(), ActionExecutorException.ErrorType.TRANSIENT, "JA001"); 224 registerError(AccessControlException.class.getName(), ActionExecutorException.ErrorType.NON_TRANSIENT, 225 "JA002"); 226 registerError(DiskChecker.DiskOutOfSpaceException.class.getName(), 227 ActionExecutorException.ErrorType.NON_TRANSIENT, "JA003"); 228 registerError(org.apache.hadoop.hdfs.protocol.QuotaExceededException.class.getName(), 229 ActionExecutorException.ErrorType.NON_TRANSIENT, "JA004"); 230 registerError(org.apache.hadoop.hdfs.server.namenode.SafeModeException.class.getName(), 231 ActionExecutorException.ErrorType.NON_TRANSIENT, "JA005"); 232 registerError(ConnectException.class.getName(), ActionExecutorException.ErrorType.TRANSIENT, " JA006"); 233 registerError(JDOMException.class.getName(), ActionExecutorException.ErrorType.ERROR, "JA007"); 234 registerError(FileNotFoundException.class.getName(), ActionExecutorException.ErrorType.ERROR, "JA008"); 235 registerError(IOException.class.getName(), ActionExecutorException.ErrorType.TRANSIENT, "JA009"); 236 } 237 238 239 /** 240 * Get the maximum allowed size of stats 241 * 242 * @return maximum size of stats 243 */ 244 public static int getMaxExternalStatsSize() { 245 return maxExternalStatsSize; 246 } 247 248 static void checkForDisallowedProps(Configuration conf, String confName) throws ActionExecutorException { 249 for (String prop : DISALLOWED_PROPERTIES) { 250 if (conf.get(prop) != null) { 251 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "JA010", 252 "Property [{0}] not allowed in action [{1}] configuration", prop, confName); 253 } 254 } 255 } 256 257 public Configuration createBaseHadoopConf(Context context, Element actionXml) { 258 return createBaseHadoopConf(context, actionXml, true); 259 } 260 261 protected Configuration createBaseHadoopConf(Context context, Element actionXml, boolean loadResources) { 262 263 Namespace ns = actionXml.getNamespace(); 264 String resourceManager; 265 final Element resourceManagerTag = actionXml.getChild("resource-manager", ns); 266 if (resourceManagerTag != null) { 267 resourceManager = resourceManagerTag.getTextTrim(); 268 } 269 else { 270 resourceManager = actionXml.getChild("job-tracker", ns).getTextTrim(); 271 } 272 273 String nameNode = actionXml.getChild("name-node", ns).getTextTrim(); 274 Configuration conf = null; 275 if (loadResources) { 276 conf = Services.get().get(HadoopAccessorService.class).createConfiguration(resourceManager); 277 } 278 else { 279 conf = new Configuration(false); 280 } 281 282 conf.set(HADOOP_USER, context.getProtoActionConf().get(WorkflowAppService.HADOOP_USER)); 283 conf.set(HADOOP_YARN_RM, resourceManager); 284 conf.set(HADOOP_NAME_NODE, nameNode); 285 conf.set("mapreduce.fileoutputcommitter.marksuccessfuljobs", "true"); 286 287 // FIXME - think about this! 288 Element e = actionXml.getChild("config-class", ns); 289 if (e != null) { 290 conf.set(LauncherAMUtils.OOZIE_ACTION_CONFIG_CLASS, e.getTextTrim()); 291 } 292 293 return conf; 294 } 295 296 protected Configuration loadHadoopDefaultResources(Context context, Element actionXml) { 297 return createBaseHadoopConf(context, actionXml); 298 } 299 300 Configuration setupLauncherConf(Configuration conf, Element actionXml, Path appPath, Context context) 301 throws ActionExecutorException { 302 try { 303 Namespace ns = actionXml.getNamespace(); 304 XConfiguration launcherConf = new XConfiguration(); 305 // Inject action defaults for launcher 306 HadoopAccessorService has = Services.get().get(HadoopAccessorService.class); 307 XConfiguration actionDefaultConf = has.createActionDefaultConf(conf.get(HADOOP_YARN_RM), getType()); 308 309 new LauncherConfigurationInjector(actionDefaultConf).inject(launcherConf); 310 311 // Inject <job-xml> and <configuration> for launcher 312 try { 313 parseJobXmlAndConfiguration(context, actionXml, appPath, launcherConf, true); 314 } catch (HadoopAccessorException ex) { 315 throw convertException(ex); 316 } catch (URISyntaxException ex) { 317 throw convertException(ex); 318 } 319 XConfiguration.copy(launcherConf, conf); 320 // Inject config-class for launcher to use for action 321 Element e = actionXml.getChild("config-class", ns); 322 if (e != null) { 323 conf.set(LauncherAMUtils.OOZIE_ACTION_CONFIG_CLASS, e.getTextTrim()); 324 } 325 checkForDisallowedProps(launcherConf, "launcher configuration"); 326 return conf; 327 } 328 catch (IOException ex) { 329 throw convertException(ex); 330 } 331 } 332 333 void injectLauncherTimelineServiceEnabled(Configuration launcherConf, Configuration actionConf) { 334 // Getting delegation token for ATS. If tez-site.xml is present in distributed cache, turn on timeline service. 335 if (actionConf.get("oozie.launcher." + HADOOP_YARN_TIMELINE_SERVICE_ENABLED) == null 336 && ConfigurationService.getBoolean(OOZIE_ACTION_LAUNCHER_PREFIX + HADOOP_YARN_TIMELINE_SERVICE_ENABLED)) { 337 String cacheFiles = launcherConf.get("mapred.cache.files"); 338 if (cacheFiles != null && cacheFiles.contains("tez-site.xml")) { 339 launcherConf.setBoolean(HADOOP_YARN_TIMELINE_SERVICE_ENABLED, true); 340 } 341 } 342 } 343 344 public static void parseJobXmlAndConfiguration(Context context, Element element, Path appPath, Configuration conf) 345 throws IOException, ActionExecutorException, HadoopAccessorException, URISyntaxException { 346 parseJobXmlAndConfiguration(context, element, appPath, conf, false); 347 } 348 349 public static void parseJobXmlAndConfiguration(Context context, Element element, Path appPath, Configuration conf, 350 boolean isLauncher) throws IOException, ActionExecutorException, HadoopAccessorException, URISyntaxException { 351 Namespace ns = element.getNamespace(); 352 @SuppressWarnings("unchecked") 353 Iterator<Element> it = element.getChildren("job-xml", ns).iterator(); 354 HashMap<String, FileSystem> filesystemsMap = new HashMap<String, FileSystem>(); 355 HadoopAccessorService has = Services.get().get(HadoopAccessorService.class); 356 while (it.hasNext()) { 357 Element e = it.next(); 358 String jobXml = e.getTextTrim(); 359 Path pathSpecified = new Path(jobXml); 360 Path path = pathSpecified.isAbsolute() ? pathSpecified : new Path(appPath, jobXml); 361 FileSystem fs; 362 if (filesystemsMap.containsKey(path.toUri().getAuthority())) { 363 fs = filesystemsMap.get(path.toUri().getAuthority()); 364 } 365 else { 366 if (path.toUri().getAuthority() != null) { 367 fs = has.createFileSystem(context.getWorkflow().getUser(), path.toUri(), 368 has.createConfiguration(path.toUri().getAuthority())); 369 } 370 else { 371 fs = context.getAppFileSystem(); 372 } 373 filesystemsMap.put(path.toUri().getAuthority(), fs); 374 } 375 Configuration jobXmlConf = new XConfiguration(fs.open(path)); 376 try { 377 String jobXmlConfString = XmlUtils.prettyPrint(jobXmlConf).toString(); 378 jobXmlConfString = XmlUtils.removeComments(jobXmlConfString); 379 jobXmlConfString = context.getELEvaluator().evaluate(jobXmlConfString, String.class); 380 jobXmlConf = new XConfiguration(new StringReader(jobXmlConfString)); 381 } 382 catch (ELEvaluationException ex) { 383 throw new ActionExecutorException(ActionExecutorException.ErrorType.TRANSIENT, "EL_EVAL_ERROR", ex 384 .getMessage(), ex); 385 } 386 catch (Exception ex) { 387 context.setErrorInfo("EL_ERROR", ex.getMessage()); 388 } 389 checkForDisallowedProps(jobXmlConf, "job-xml"); 390 if (isLauncher) { 391 new LauncherConfigurationInjector(jobXmlConf).inject(conf); 392 } else { 393 XConfiguration.copy(jobXmlConf, conf); 394 } 395 } 396 Element e = element.getChild("configuration", ns); 397 if (e != null) { 398 String strConf = XmlUtils.prettyPrint(e).toString(); 399 XConfiguration inlineConf = new XConfiguration(new StringReader(strConf)); 400 checkForDisallowedProps(inlineConf, "inline configuration"); 401 if (isLauncher) { 402 new LauncherConfigurationInjector(inlineConf).inject(conf); 403 } else { 404 XConfiguration.copy(inlineConf, conf); 405 } 406 } 407 } 408 409 Configuration setupActionConf(Configuration actionConf, Context context, Element actionXml, Path appPath) 410 throws ActionExecutorException { 411 try { 412 HadoopAccessorService has = Services.get().get(HadoopAccessorService.class); 413 XConfiguration actionDefaults = has.createActionDefaultConf(actionConf.get(HADOOP_YARN_RM), getType()); 414 XConfiguration.copy(actionDefaults, actionConf); 415 has.checkSupportedFilesystem(appPath.toUri()); 416 417 // Set the Java Main Class for the Java action to give to the Java launcher 418 setJavaMain(actionConf, actionXml); 419 420 parseJobXmlAndConfiguration(context, actionXml, appPath, actionConf); 421 422 // set cancel.delegation.token in actionConf that child job doesn't cancel delegation token 423 actionConf.setBoolean("mapreduce.job.complete.cancel.delegation.tokens", false); 424 setRootLoggerLevel(actionConf); 425 return actionConf; 426 } 427 catch (IOException ex) { 428 throw convertException(ex); 429 } 430 catch (HadoopAccessorException ex) { 431 throw convertException(ex); 432 } 433 catch (URISyntaxException ex) { 434 throw convertException(ex); 435 } 436 } 437 438 /** 439 * Set root log level property in actionConf 440 * @param actionConf 441 */ 442 void setRootLoggerLevel(Configuration actionConf) { 443 String oozieActionTypeRootLogger = "oozie.action." + getType() + LauncherAMUtils.ROOT_LOGGER_LEVEL; 444 String oozieActionRootLogger = "oozie.action." + LauncherAMUtils.ROOT_LOGGER_LEVEL; 445 446 // check if root log level has already mentioned in action configuration 447 String rootLogLevel = actionConf.get(oozieActionTypeRootLogger, actionConf.get(oozieActionRootLogger)); 448 if (rootLogLevel != null) { 449 // root log level is mentioned in action configuration 450 return; 451 } 452 453 // set the root log level which is mentioned in oozie default 454 rootLogLevel = ConfigurationService.get(oozieActionTypeRootLogger); 455 if (rootLogLevel != null && rootLogLevel.length() > 0) { 456 actionConf.set(oozieActionRootLogger, rootLogLevel); 457 } 458 else { 459 rootLogLevel = ConfigurationService.get(oozieActionRootLogger); 460 if (rootLogLevel != null && rootLogLevel.length() > 0) { 461 actionConf.set(oozieActionRootLogger, rootLogLevel); 462 } 463 } 464 } 465 466 Configuration addToCache(Configuration conf, Path appPath, String filePath, boolean archive) 467 throws ActionExecutorException { 468 469 URI uri = null; 470 try { 471 uri = new URI(getTrimmedEncodedPath(filePath)); 472 URI baseUri = appPath.toUri(); 473 if (uri.getScheme() == null) { 474 String resolvedPath = uri.getPath(); 475 if (!resolvedPath.startsWith("/")) { 476 resolvedPath = baseUri.getPath() + "/" + resolvedPath; 477 } 478 uri = new URI(baseUri.getScheme(), baseUri.getAuthority(), resolvedPath, uri.getQuery(), uri.getFragment()); 479 } 480 if (archive) { 481 DistributedCache.addCacheArchive(uri.normalize(), conf); 482 } 483 else { 484 String fileName = filePath.substring(filePath.lastIndexOf("/") + 1); 485 if (fileName.endsWith(".so") || fileName.contains(".so.")) { // .so files 486 uri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), uri.getQuery(), fileName); 487 DistributedCache.addCacheFile(uri.normalize(), conf); 488 } 489 else if (fileName.endsWith(".jar")) { // .jar files 490 if (!fileName.contains("#")) { 491 String user = conf.get("user.name"); 492 493 if (FSUtils.isNotLocalFile(fileName)) { 494 Path pathToAdd = new Path(uri.normalize()); 495 Services.get().get(HadoopAccessorService.class).addFileToClassPath(user, pathToAdd, conf); 496 } 497 } 498 else { 499 DistributedCache.addCacheFile(uri.normalize(), conf); 500 } 501 } 502 else { // regular files 503 if (!fileName.contains("#")) { 504 uri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), uri.getQuery(), fileName); 505 } 506 DistributedCache.addCacheFile(uri.normalize(), conf); 507 } 508 } 509 DistributedCache.createSymlink(conf); 510 return conf; 511 } 512 catch (Exception ex) { 513 LOG.debug("Errors when add to DistributedCache. Path=" + 514 Objects.toString(uri, "<null>") + ", archive=" + archive + ", conf=" + 515 XmlUtils.prettyPrint(conf).toString()); 516 throw convertException(ex); 517 } 518 } 519 520 public void prepareActionDir(FileSystem actionFs, Context context) throws ActionExecutorException { 521 try { 522 Path actionDir = context.getActionDir(); 523 Path tempActionDir = new Path(actionDir.getParent(), actionDir.getName() + ".tmp"); 524 if (!actionFs.exists(actionDir)) { 525 try { 526 actionFs.mkdirs(tempActionDir); 527 actionFs.rename(tempActionDir, actionDir); 528 } 529 catch (IOException ex) { 530 actionFs.delete(tempActionDir, true); 531 actionFs.delete(actionDir, true); 532 throw ex; 533 } 534 } 535 } 536 catch (Exception ex) { 537 throw convertException(ex); 538 } 539 } 540 541 void cleanUpActionDir(FileSystem actionFs, Context context) throws ActionExecutorException { 542 try { 543 Path actionDir = context.getActionDir(); 544 if (!context.getProtoActionConf().getBoolean(WorkflowXCommand.KEEP_WF_ACTION_DIR, false) 545 && actionFs.exists(actionDir)) { 546 actionFs.delete(actionDir, true); 547 } 548 } 549 catch (Exception ex) { 550 throw convertException(ex); 551 } 552 } 553 554 protected void addShareLib(Configuration conf, String[] actionShareLibNames) 555 throws ActionExecutorException { 556 Set<String> confSet = new HashSet<String>(Arrays.asList(getShareLibFilesForActionConf() == null ? new String[0] 557 : getShareLibFilesForActionConf())); 558 559 Set<Path> sharelibList = new HashSet<Path>(); 560 561 if (actionShareLibNames != null) { 562 try { 563 ShareLibService shareLibService = Services.get().get(ShareLibService.class); 564 FileSystem fs = shareLibService.getFileSystem(); 565 if (fs != null) { 566 for (String actionShareLibName : actionShareLibNames) { 567 List<Path> listOfPaths = shareLibService.getShareLibJars(actionShareLibName); 568 if (listOfPaths != null && !listOfPaths.isEmpty()) { 569 for (Path actionLibPath : listOfPaths) { 570 String fragmentName = new URI(actionLibPath.toString()).getFragment(); 571 String fileName = fragmentName == null ? actionLibPath.getName() : fragmentName; 572 if (confSet.contains(fileName)) { 573 Configuration jobXmlConf = shareLibService.getShareLibConf(actionShareLibName, 574 actionLibPath); 575 if (jobXmlConf != null) { 576 checkForDisallowedProps(jobXmlConf, actionLibPath.getName()); 577 XConfiguration.injectDefaults(jobXmlConf, conf); 578 LOG.trace("Adding properties of " + actionLibPath + " to job conf"); 579 } 580 } 581 else { 582 // Filtering out duplicate jars or files 583 sharelibList.add(new Path(actionLibPath.toUri()) { 584 @Override 585 public int hashCode() { 586 return getName().hashCode(); 587 } 588 @Override 589 public String getName() { 590 try { 591 return (new URI(toString())).getFragment() == null ? new Path(toUri()).getName() 592 : (new URI(toString())).getFragment(); 593 } 594 catch (URISyntaxException e) { 595 throw new RuntimeException(e); 596 } 597 } 598 @Override 599 public boolean equals(Object input) { 600 if (input == null) { 601 return false; 602 } 603 if (input == this) { 604 return true; 605 } 606 if (!(input instanceof Path)) { 607 return false; 608 } 609 return getName().equals(((Path) input).getName()); 610 } 611 }); 612 } 613 } 614 } 615 } 616 } 617 addLibPathsToCache(conf, sharelibList); 618 } 619 catch (URISyntaxException ex) { 620 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "Error configuring sharelib", 621 ex.getMessage()); 622 } 623 catch (IOException ex) { 624 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "It should never happen", 625 ex.getMessage()); 626 } 627 } 628 } 629 630 protected void addSystemShareLibForAction(Configuration conf) throws ActionExecutorException { 631 ShareLibService shareLibService = Services.get().get(ShareLibService.class); 632 // ShareLibService is null for test cases 633 if (shareLibService != null) { 634 try { 635 List<Path> listOfPaths = shareLibService.getSystemLibJars(JavaActionExecutor.OOZIE_COMMON_LIBDIR); 636 if (listOfPaths.isEmpty()) { 637 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "EJ001", 638 "Could not locate Oozie sharelib"); 639 } 640 addLibPathsToClassPath(conf, listOfPaths); 641 addLibPathsToClassPath(conf, shareLibService.getSystemLibJars(getType())); 642 } 643 catch (IOException ex) { 644 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "It should never happen", 645 ex.getMessage()); 646 } 647 } 648 } 649 650 private void addLibPathsToClassPath(Configuration conf, List<Path> listOfPaths) 651 throws IOException, ActionExecutorException { 652 addLibPathsToClassPathOrCache(conf, listOfPaths, false); 653 } 654 655 private void addLibPathsToCache(Configuration conf, Set<Path> sharelibList) 656 throws IOException, ActionExecutorException { 657 addLibPathsToClassPathOrCache(conf, sharelibList, true); 658 } 659 660 661 private void addLibPathsToClassPathOrCache(Configuration conf, Collection<Path> sharelibList, boolean isAddToCache) 662 throws IOException, ActionExecutorException { 663 664 for (Path libPath : sharelibList) { 665 if (FSUtils.isLocalFile(libPath.toString())) { 666 conf = ClasspathUtils.addToClasspathFromLocalShareLib(conf, libPath); 667 } 668 else { 669 if (isAddToCache) { 670 addToCache(conf, libPath, libPath.toUri().getPath(), false); 671 } 672 else { 673 FileSystem fs = libPath.getFileSystem(conf); 674 JobUtils.addFileToClassPath(libPath, conf, fs); 675 DistributedCache.createSymlink(conf); 676 } 677 } 678 } 679 } 680 681 protected void addActionLibs(Path appPath, Configuration conf) throws ActionExecutorException { 682 String[] actionLibsStrArr = conf.getStrings("oozie.launcher.oozie.libpath"); 683 if (actionLibsStrArr != null) { 684 try { 685 for (String actionLibsStr : actionLibsStrArr) { 686 actionLibsStr = actionLibsStr.trim(); 687 if (actionLibsStr.length() > 0) 688 { 689 Path actionLibsPath = new Path(actionLibsStr); 690 String user = conf.get("user.name"); 691 FileSystem fs = Services.get().get(HadoopAccessorService.class).createFileSystem(user, 692 appPath.toUri(), conf); 693 if (fs.exists(actionLibsPath)) { 694 FileStatus[] files = fs.listStatus(actionLibsPath); 695 for (FileStatus file : files) { 696 addToCache(conf, appPath, file.getPath().toUri().getPath(), false); 697 } 698 } 699 } 700 } 701 } 702 catch (HadoopAccessorException ex){ 703 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, 704 ex.getErrorCode().toString(), ex.getMessage()); 705 } 706 catch (IOException ex){ 707 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, 708 "It should never happen", ex.getMessage()); 709 } 710 } 711 } 712 713 @SuppressWarnings("unchecked") 714 public void setLibFilesArchives(Context context, Element actionXml, Path appPath, Configuration conf) 715 throws ActionExecutorException { 716 Configuration proto = context.getProtoActionConf(); 717 718 // Workflow lib/ 719 String[] paths = proto.getStrings(WorkflowAppService.APP_LIB_PATH_LIST); 720 if (paths != null) { 721 for (String path : paths) { 722 addToCache(conf, appPath, path, false); 723 } 724 } 725 726 // Action libs 727 addActionLibs(appPath, conf); 728 729 // files and archives defined in the action 730 for (Element eProp : (List<Element>) actionXml.getChildren()) { 731 if (eProp.getName().equals("file")) { 732 String[] filePaths = eProp.getTextTrim().split(","); 733 for (String path : filePaths) { 734 addToCache(conf, appPath, path, false); 735 } 736 } 737 else if (eProp.getName().equals("archive")) { 738 String[] archivePaths = eProp.getTextTrim().split(","); 739 for (String path : archivePaths){ 740 addToCache(conf, appPath, path.trim(), true); 741 } 742 } 743 } 744 745 addAllShareLibs(appPath, conf, context, actionXml); 746 } 747 748 @VisibleForTesting 749 protected static String getTrimmedEncodedPath(String path) { 750 return path.trim().replace(" ", "%20"); 751 } 752 753 // Adds action specific share libs and common share libs 754 private void addAllShareLibs(Path appPath, Configuration conf, Context context, Element actionXml) 755 throws ActionExecutorException { 756 // Add action specific share libs 757 addActionShareLib(appPath, conf, context, actionXml); 758 // Add common sharelibs for Oozie and launcher jars 759 addSystemShareLibForAction(conf); 760 } 761 762 private void addActionShareLib(Path appPath, Configuration conf, Context context, Element actionXml) 763 throws ActionExecutorException { 764 XConfiguration wfJobConf = null; 765 try { 766 wfJobConf = getWorkflowConf(context); 767 } 768 catch (IOException ioe) { 769 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "It should never happen", 770 ioe.getMessage()); 771 } 772 // Action sharelibs are only added if user has specified to use system libpath 773 if (conf.get(OozieClient.USE_SYSTEM_LIBPATH) == null) { 774 if (wfJobConf.getBoolean(OozieClient.USE_SYSTEM_LIBPATH, 775 ConfigurationService.getBoolean(OozieClient.USE_SYSTEM_LIBPATH))) { 776 // add action specific sharelibs 777 addShareLib(conf, getShareLibNames(context, actionXml, conf)); 778 } 779 } 780 else { 781 if (conf.getBoolean(OozieClient.USE_SYSTEM_LIBPATH, false)) { 782 // add action specific sharelibs 783 addShareLib(conf, getShareLibNames(context, actionXml, conf)); 784 } 785 } 786 } 787 788 789 protected String getLauncherMain(Configuration launcherConf, Element actionXml) { 790 return launcherConf.get(LauncherAM.CONF_OOZIE_ACTION_MAIN_CLASS, JavaMain.class.getName()); 791 } 792 793 private void setJavaMain(Configuration actionConf, Element actionXml) { 794 Namespace ns = actionXml.getNamespace(); 795 Element e = actionXml.getChild("main-class", ns); 796 if (e != null) { 797 actionConf.set(JavaMain.JAVA_MAIN_CLASS, e.getTextTrim()); 798 } 799 } 800 801 private static final String QUEUE_NAME = "mapred.job.queue.name"; 802 803 private static final Set<String> SPECIAL_PROPERTIES = new HashSet<String>(); 804 805 static { 806 SPECIAL_PROPERTIES.add(QUEUE_NAME); 807 SPECIAL_PROPERTIES.add(ACL_VIEW_JOB); 808 SPECIAL_PROPERTIES.add(ACL_MODIFY_JOB); 809 } 810 811 @SuppressWarnings("unchecked") 812 Configuration createLauncherConf(FileSystem actionFs, Context context, WorkflowAction action, Element actionXml, 813 Configuration actionConf) throws ActionExecutorException { 814 try { 815 816 // app path could be a file 817 Path appPathRoot = new Path(context.getWorkflow().getAppPath()); 818 if (actionFs.isFile(appPathRoot)) { 819 appPathRoot = appPathRoot.getParent(); 820 } 821 822 // launcher job configuration 823 Configuration launcherJobConf = createBaseHadoopConf(context, actionXml); 824 // cancel delegation token on a launcher job which stays alive till child job(s) finishes 825 // otherwise (in mapred action), doesn't cancel not to disturb running child job 826 launcherJobConf.setBoolean("mapreduce.job.complete.cancel.delegation.tokens", true); 827 setupLauncherConf(launcherJobConf, actionXml, appPathRoot, context); 828 829 // Properties for when a launcher job's AM gets restarted 830 if (ConfigurationService.getBoolean(HADOOP_YARN_KILL_CHILD_JOBS_ON_AMRESTART)) { 831 // launcher time filter is required to prune the search of launcher tag. 832 // Setting coordinator action nominal time as launcher time as it child job cannot launch before nominal 833 // time. Workflow created time is good enough when workflow is running independently or workflow is 834 // rerunning from failed node. 835 long launcherTime = System.currentTimeMillis(); 836 String coordActionNominalTime = context.getProtoActionConf().get( 837 CoordActionStartXCommand.OOZIE_COORD_ACTION_NOMINAL_TIME); 838 if (coordActionNominalTime != null) { 839 launcherTime = Long.parseLong(coordActionNominalTime); 840 } 841 else if (context.getWorkflow().getCreatedTime() != null) { 842 launcherTime = context.getWorkflow().getCreatedTime().getTime(); 843 } 844 String actionYarnTag = getActionYarnTag(getWorkflowConf(context), context.getWorkflow(), action); 845 LauncherHelper.setupYarnRestartHandling(launcherJobConf, actionConf, actionYarnTag, launcherTime); 846 } 847 else { 848 LOG.info(MessageFormat.format("{0} is set to false, not setting YARN restart properties", 849 HADOOP_YARN_KILL_CHILD_JOBS_ON_AMRESTART)); 850 } 851 852 String actionShareLibProperty = actionConf.get(ACTION_SHARELIB_FOR + getType()); 853 if (actionShareLibProperty != null) { 854 launcherJobConf.set(ACTION_SHARELIB_FOR + getType(), actionShareLibProperty); 855 } 856 setLibFilesArchives(context, actionXml, appPathRoot, launcherJobConf); 857 858 // Inject Oozie job information if enabled. 859 injectJobInfo(launcherJobConf, actionConf, context, action); 860 861 injectLauncherCallback(context, launcherJobConf); 862 863 String jobId = context.getWorkflow().getId(); 864 String actionId = action.getId(); 865 Path actionDir = context.getActionDir(); 866 String recoveryId = context.getRecoveryId(); 867 868 // Getting the prepare XML from the action XML 869 Namespace ns = actionXml.getNamespace(); 870 Element prepareElement = actionXml.getChild("prepare", ns); 871 String prepareXML = ""; 872 if (prepareElement != null) { 873 if (prepareElement.getChildren().size() > 0) { 874 prepareXML = XmlUtils.prettyPrint(prepareElement).toString().trim(); 875 } 876 } 877 LauncherHelper.setupLauncherInfo(launcherJobConf, jobId, actionId, actionDir, recoveryId, actionConf, 878 prepareXML); 879 880 // Set the launcher Main Class 881 LauncherHelper.setupMainClass(launcherJobConf, getLauncherMain(launcherJobConf, actionXml)); 882 LauncherHelper.setupLauncherURIHandlerConf(launcherJobConf); 883 LauncherHelper.setupMaxOutputData(launcherJobConf, getMaxOutputData(actionConf)); 884 LauncherHelper.setupMaxExternalStatsSize(launcherJobConf, maxExternalStatsSize); 885 LauncherHelper.setupMaxFSGlob(launcherJobConf, maxFSGlobMax); 886 887 List<Element> list = actionXml.getChildren("arg", ns); 888 String[] args = new String[list.size()]; 889 for (int i = 0; i < list.size(); i++) { 890 args[i] = list.get(i).getTextTrim(); 891 } 892 LauncherHelper.setupMainArguments(launcherJobConf, args); 893 // backward compatibility flag - see OOZIE-2872 894 boolean nullArgsAllowed = ConfigurationService.getBoolean(LauncherAMUtils.CONF_OOZIE_NULL_ARGS_ALLOWED); 895 launcherJobConf.setBoolean(LauncherAMUtils.CONF_OOZIE_NULL_ARGS_ALLOWED, nullArgsAllowed); 896 897 // Make mapred.child.java.opts and mapreduce.map.java.opts equal, but give values from the latter priority; also append 898 // <java-opt> and <java-opts> and give those highest priority 899 StringBuilder opts = new StringBuilder(launcherJobConf.get(HADOOP_CHILD_JAVA_OPTS, "")); 900 if (launcherJobConf.get(HADOOP_MAP_JAVA_OPTS) != null) { 901 opts.append(" ").append(launcherJobConf.get(HADOOP_MAP_JAVA_OPTS)); 902 } 903 904 List<Element> javaopts = actionXml.getChildren("java-opt", ns); 905 906 // Either one or more <java-opt> element or one <java-opts> can be present since oozie-workflow-0.4 907 if (!javaopts.isEmpty()) { 908 for (Element opt : javaopts) { 909 opts.append(" ").append(opt.getTextTrim()); 910 } 911 } 912 else { 913 Element opt = actionXml.getChild("java-opts", ns); 914 if (opt != null) { 915 opts.append(" ").append(opt.getTextTrim()); 916 } 917 } 918 launcherJobConf.set(HADOOP_CHILD_JAVA_OPTS, opts.toString().trim()); 919 launcherJobConf.set(HADOOP_MAP_JAVA_OPTS, opts.toString().trim()); 920 921 injectLauncherTimelineServiceEnabled(launcherJobConf, actionConf); 922 923 // properties from action that are needed by the launcher (e.g. QUEUE NAME, ACLs) 924 // maybe we should add queue to the WF schema, below job-tracker 925 actionConfToLauncherConf(actionConf, launcherJobConf); 926 927 return launcherJobConf; 928 } 929 catch (Exception ex) { 930 throw convertException(ex); 931 } 932 } 933 934 @VisibleForTesting 935 protected static int getMaxOutputData(Configuration actionConf) { 936 String userMaxActionOutputLen = actionConf.get("oozie.action.max.output.data"); 937 if (userMaxActionOutputLen != null) { 938 Integer i = Ints.tryParse(userMaxActionOutputLen); 939 return i != null ? i : maxActionOutputLen; 940 } 941 return maxActionOutputLen; 942 } 943 944 protected void injectCallback(Context context, Configuration conf) { 945 String callback = context.getCallbackUrl(LauncherAMCallbackNotifier.OOZIE_LAUNCHER_CALLBACK_JOBSTATUS_TOKEN); 946 conf.set(LauncherAMCallbackNotifier.OOZIE_LAUNCHER_CALLBACK_URL, callback); 947 } 948 949 void injectActionCallback(Context context, Configuration actionConf) { 950 // action callback needs to be injected only for mapreduce actions. 951 } 952 953 void injectLauncherCallback(Context context, Configuration launcherConf) { 954 injectCallback(context, launcherConf); 955 } 956 957 private void actionConfToLauncherConf(Configuration actionConf, Configuration launcherConf) { 958 for (String name : SPECIAL_PROPERTIES) { 959 if (actionConf.get(name) != null && launcherConf.get("oozie.launcher." + name) == null) { 960 launcherConf.set(name, actionConf.get(name)); 961 } 962 } 963 } 964 965 public void submitLauncher(FileSystem actionFs, final Context context, WorkflowAction action) throws ActionExecutorException { 966 YarnClient yarnClient = null; 967 try { 968 Path appPathRoot = new Path(context.getWorkflow().getAppPath()); 969 970 // app path could be a file 971 if (actionFs.isFile(appPathRoot)) { 972 appPathRoot = appPathRoot.getParent(); 973 } 974 975 Element actionXml = XmlUtils.parseXml(action.getConf()); 976 LOG.debug("ActionXML: {0}", action.getConf()); 977 978 // action job configuration 979 Configuration actionConf = loadHadoopDefaultResources(context, actionXml); 980 setupActionConf(actionConf, context, actionXml, appPathRoot); 981 addAppNameContext(action, context); 982 LOG.debug("Setting LibFilesArchives "); 983 setLibFilesArchives(context, actionXml, appPathRoot, actionConf); 984 985 String jobName = actionConf.get(HADOOP_JOB_NAME); 986 if (jobName == null || jobName.isEmpty()) { 987 jobName = XLog.format("oozie:action:T={0}:W={1}:A={2}:ID={3}", 988 getType(), context.getWorkflow().getAppName(), 989 action.getName(), context.getWorkflow().getId()); 990 actionConf.set(HADOOP_JOB_NAME, jobName); 991 } 992 993 injectActionCallback(context, actionConf); 994 995 if(actionConf.get(ACL_MODIFY_JOB) == null || actionConf.get(ACL_MODIFY_JOB).trim().equals("")) { 996 // ONLY in the case where user has not given the 997 // modify-job ACL specifically 998 if (context.getWorkflow().getAcl() != null) { 999 // setting the group owning the Oozie job to allow anybody in that 1000 // group to modify the jobs. 1001 actionConf.set(ACL_MODIFY_JOB, context.getWorkflow().getAcl()); 1002 } 1003 } 1004 1005 Credentials credentials = new Credentials(); 1006 Configuration launcherConf = createLauncherConf(actionFs, context, action, actionXml, actionConf); 1007 yarnClient = createYarnClient(context, launcherConf); 1008 Map<String, CredentialsProperties> credentialsProperties = setCredentialPropertyToActionConf(context, 1009 action, actionConf); 1010 if (UserGroupInformation.isSecurityEnabled()) { 1011 addHadoopCredentialPropertiesToActionConf(credentialsProperties); 1012 } 1013 // Adding if action need to set more credential tokens 1014 Configuration credentialsConf = new Configuration(false); 1015 XConfiguration.copy(actionConf, credentialsConf); 1016 setCredentialTokens(credentials, credentialsConf, context, action, credentialsProperties); 1017 1018 // copy back new entries from credentialsConf 1019 for (Entry<String, String> entry : credentialsConf) { 1020 if (actionConf.get(entry.getKey()) == null) { 1021 actionConf.set(entry.getKey(), entry.getValue()); 1022 } 1023 } 1024 String consoleUrl; 1025 String launcherId = LauncherHelper.getRecoveryId(launcherConf, context.getActionDir(), context 1026 .getRecoveryId()); 1027 1028 removeHBaseSettingFromOozieDefaultResource(launcherConf); 1029 removeHBaseSettingFromOozieDefaultResource(actionConf); 1030 1031 1032 boolean alreadyRunning = launcherId != null; 1033 1034 // if user-retry is on, always submit new launcher 1035 boolean isUserRetry = ((WorkflowActionBean)action).isUserRetry(); 1036 LOG.debug("Creating yarnClient for action {0}", action.getId()); 1037 1038 if (alreadyRunning && !isUserRetry) { 1039 try { 1040 ApplicationId appId = ConverterUtils.toApplicationId(launcherId); 1041 ApplicationReport report = yarnClient.getApplicationReport(appId); 1042 consoleUrl = report.getTrackingUrl(); 1043 } catch (RemoteException e) { 1044 // caught when the application id does not exist 1045 LOG.error("Got RemoteException from YARN", e); 1046 String jobTracker = launcherConf.get(HADOOP_YARN_RM); 1047 throw new ActionExecutorException(ActionExecutorException.ErrorType.ERROR, "JA017", 1048 "unknown job [{0}@{1}], cannot recover", launcherId, jobTracker); 1049 } 1050 } 1051 else { 1052 YarnClientApplication newApp = yarnClient.createApplication(); 1053 ApplicationId appId = newApp.getNewApplicationResponse().getApplicationId(); 1054 ApplicationSubmissionContext appContext = 1055 createAppSubmissionContext(appId, launcherConf, context, actionConf, action.getName(), 1056 credentials, actionXml); 1057 yarnClient.submitApplication(appContext); 1058 1059 launcherId = appId.toString(); 1060 LOG.debug("After submission get the launcherId [{0}]", launcherId); 1061 ApplicationReport appReport = yarnClient.getApplicationReport(appId); 1062 consoleUrl = appReport.getTrackingUrl(); 1063 } 1064 1065 String jobTracker = launcherConf.get(HADOOP_YARN_RM); 1066 context.setStartData(launcherId, jobTracker, consoleUrl); 1067 } 1068 catch (Exception ex) { 1069 throw convertException(ex); 1070 } 1071 finally { 1072 if (yarnClient != null) { 1073 Closeables.closeQuietly(yarnClient); 1074 } 1075 } 1076 } 1077 1078 private void removeHBaseSettingFromOozieDefaultResource(final Configuration jobConf) { 1079 final String[] propertySources = jobConf.getPropertySources(HbaseCredentials.HBASE_USE_DYNAMIC_JARS); 1080 if (propertySources != null && propertySources.length > 0 && 1081 propertySources[0].contains(HbaseCredentials.OOZIE_HBASE_CLIENT_SITE_XML)) { 1082 jobConf.unset(HbaseCredentials.HBASE_USE_DYNAMIC_JARS); 1083 LOG.debug(String.format("Unset [%s] inserted from default Oozie resource XML [%s]", 1084 HbaseCredentials.HBASE_USE_DYNAMIC_JARS, HbaseCredentials.OOZIE_HBASE_CLIENT_SITE_XML)); 1085 } 1086 } 1087 1088 protected void addAppNameContext(WorkflowAction action, Context context) { 1089 String oozieActionName = String.format("oozie:launcher:T=%s:W=%s:A=%s:ID=%s", 1090 getType(), 1091 context.getWorkflow().getAppName(), 1092 action.getName(), 1093 context.getWorkflow().getId()); 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 String actionName, 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, actionName, 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_ATTEMPS); 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(Context context, String actionName, ApplicationSubmissionContext appContext) { 1276 String jobName = XLog.format("oozie:launcher:T={0}:W={1}:A={2}:ID={3}", getType(), 1277 context.getWorkflow().getAppName(), actionName, 1278 context.getWorkflow().getId()); 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 ApplicationReport appReport = 1635 yarnClient.getApplicationReport(ConverterUtils.toApplicationId(action.getExternalId())); 1636 YarnApplicationState appState = appReport.getYarnApplicationState(); 1637 if (appState == YarnApplicationState.FAILED || appState == YarnApplicationState.FINISHED 1638 || appState == YarnApplicationState.KILLED) { 1639 appStatus = appReport.getFinalApplicationStatus(); 1640 } 1641 1642 } catch (Exception ye) { 1643 LOG.warn("Exception occurred while checking Launcher AM status; will try checking action data file instead ", ye); 1644 // Fallback to action data file if we can't find the Launcher AM (maybe it got purged) 1645 fallback = true; 1646 } 1647 if (appStatus != null || fallback) { 1648 Path actionDir = context.getActionDir(); 1649 // load sequence file into object 1650 Map<String, String> actionData = LauncherHelper.getActionData(actionFs, actionDir, jobConf); 1651 if (fallback) { 1652 String finalStatus = actionData.get(LauncherAM.ACTION_DATA_FINAL_STATUS); 1653 if (finalStatus != null) { 1654 appStatus = FinalApplicationStatus.valueOf(finalStatus); 1655 } else { 1656 context.setExecutionData(FAILED, null); 1657 throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "JA017", 1658 "Unknown hadoop job [{0}] associated with action [{1}] and couldn't determine status from" + 1659 " action data. Failing this action!", action.getExternalId(), action.getId()); 1660 } 1661 } 1662 1663 String externalID = actionData.get(LauncherAM.ACTION_DATA_NEW_ID); // MapReduce was launched 1664 if (externalID != null) { 1665 context.setExternalChildIDs(externalID); 1666 LOG.info(XLog.STD, "Hadoop Job was launched : [{0}]", externalID); 1667 } 1668 1669 // Multiple child IDs - Pig or Hive action 1670 String externalIDs = actionData.get(LauncherAM.ACTION_DATA_EXTERNAL_CHILD_IDS); 1671 if (externalIDs != null) { 1672 context.setExternalChildIDs(externalIDs); 1673 LOG.info(XLog.STD, "External Child IDs : [{0}]", externalIDs); 1674 1675 } 1676 1677 LOG.info(XLog.STD, "action completed, external ID [{0}]", action.getExternalId()); 1678 context.setExecutionData(appStatus.toString(), null); 1679 if (appStatus == FinalApplicationStatus.SUCCEEDED) { 1680 if (getCaptureOutput(action) && LauncherHelper.hasOutputData(actionData)) { 1681 context.setExecutionData(SUCCEEDED, PropertiesUtils.stringToProperties(actionData 1682 .get(LauncherAM.ACTION_DATA_OUTPUT_PROPS))); 1683 LOG.info(XLog.STD, "action produced output"); 1684 } 1685 else { 1686 context.setExecutionData(SUCCEEDED, null); 1687 } 1688 if (LauncherHelper.hasStatsData(actionData)) { 1689 context.setExecutionStats(actionData.get(LauncherAM.ACTION_DATA_STATS)); 1690 LOG.info(XLog.STD, "action produced stats"); 1691 } 1692 getActionData(actionFs, action, context); 1693 } 1694 else { 1695 String errorReason; 1696 if (actionData.containsKey(LauncherAM.ACTION_DATA_ERROR_PROPS)) { 1697 Properties props = PropertiesUtils.stringToProperties(actionData 1698 .get(LauncherAM.ACTION_DATA_ERROR_PROPS)); 1699 String errorCode = props.getProperty("error.code"); 1700 if ("0".equals(errorCode)) { 1701 errorCode = "JA018"; 1702 } 1703 if ("-1".equals(errorCode)) { 1704 errorCode = "JA019"; 1705 } 1706 errorReason = props.getProperty("error.reason"); 1707 LOG.warn("Launcher ERROR, reason: {0}", errorReason); 1708 String exMsg = props.getProperty("exception.message"); 1709 String errorInfo = (exMsg != null) ? exMsg : errorReason; 1710 context.setErrorInfo(errorCode, errorInfo); 1711 String exStackTrace = props.getProperty("exception.stacktrace"); 1712 if (exMsg != null) { 1713 LOG.warn("Launcher exception: {0}{E}{1}", exMsg, exStackTrace); 1714 } 1715 } 1716 else { 1717 errorReason = XLog.format("Launcher AM died, check Hadoop LOG for job [{0}:{1}]", action 1718 .getTrackerUri(), action.getExternalId()); 1719 LOG.warn(errorReason); 1720 } 1721 context.setExecutionData(FAILED_KILLED, null); 1722 } 1723 } 1724 else { 1725 context.setExternalStatus(YarnApplicationState.RUNNING.toString()); 1726 LOG.info(XLog.STD, "checking action, hadoop job ID [{0}] status [RUNNING]", 1727 action.getExternalId()); 1728 } 1729 } 1730 catch (Exception ex) { 1731 LOG.warn("Exception in check(). Message[{0}]", ex.getMessage(), ex); 1732 throw convertException(ex); 1733 } 1734 finally { 1735 if (yarnClient != null) { 1736 IOUtils.closeQuietly(yarnClient); 1737 } 1738 } 1739 } 1740 1741 /** 1742 * Get the output data of an action. Subclasses should override this method 1743 * to get action specific output data. 1744 * @param actionFs the FileSystem object 1745 * @param action the Workflow action 1746 * @param context executor context 1747 * @throws org.apache.oozie.service.HadoopAccessorException 1748 * @throws org.jdom.JDOMException 1749 * @throws java.io.IOException 1750 * @throws java.net.URISyntaxException 1751 * 1752 */ 1753 protected void getActionData(FileSystem actionFs, WorkflowAction action, Context context) 1754 throws HadoopAccessorException, JDOMException, IOException, URISyntaxException { 1755 } 1756 1757 protected boolean getCaptureOutput(WorkflowAction action) throws JDOMException { 1758 Element eConf = XmlUtils.parseXml(action.getConf()); 1759 Namespace ns = eConf.getNamespace(); 1760 Element captureOutput = eConf.getChild("capture-output", ns); 1761 return captureOutput != null; 1762 } 1763 1764 @Override 1765 public void kill(Context context, WorkflowAction action) throws ActionExecutorException { 1766 YarnClient yarnClient = null; 1767 try { 1768 Element actionXml = XmlUtils.parseXml(action.getConf()); 1769 final Configuration jobConf = createBaseHadoopConf(context, actionXml); 1770 String launcherTag = getActionYarnTag(context, action); 1771 jobConf.set(LauncherMain.CHILD_MAPREDUCE_JOB_TAGS, LauncherHelper.getTag(launcherTag)); 1772 yarnClient = createYarnClient(context, jobConf); 1773 if(action.getExternalId() != null) { 1774 try { 1775 LOG.info("Killing action {0}'s external application {1}", action.getId(), action.getExternalId()); 1776 yarnClient.killApplication(ConverterUtils.toApplicationId(action.getExternalId())); 1777 } catch (Exception e) { 1778 LOG.warn("Could not kill {0}", action.getExternalId(), e); 1779 } 1780 } 1781 String externalChildIDs = action.getExternalChildIDs(); 1782 if(externalChildIDs != null) { 1783 for(String childId : externalChildIDs.split(",")) { 1784 try { 1785 LOG.info("Killing action {0}'s external child application {1}", action.getId(), childId); 1786 yarnClient.killApplication(ConverterUtils.toApplicationId(childId.trim())); 1787 } catch (Exception e) { 1788 LOG.warn("Could not kill external child of {0}, {1}", action.getExternalId(), 1789 childId, e); 1790 } 1791 } 1792 } 1793 for(ApplicationId id : LauncherMain.getChildYarnJobs(jobConf, ApplicationsRequestScope.ALL, 1794 action.getStartTime().getTime())){ 1795 try { 1796 LOG.info("Killing action {0}'s external child application {1} based on tags", 1797 action.getId(), id.toString()); 1798 yarnClient.killApplication(id); 1799 } catch (Exception e) { 1800 LOG.warn("Could not kill child of {0}, {1}", action.getExternalId(), id, e); 1801 } 1802 } 1803 1804 context.setExternalStatus(KILLED); 1805 context.setExecutionData(KILLED, null); 1806 } catch (Exception ex) { 1807 LOG.error("Error when killing YARN application", ex); 1808 throw convertException(ex); 1809 } finally { 1810 try { 1811 FileSystem actionFs = context.getAppFileSystem(); 1812 cleanUpActionDir(actionFs, context); 1813 Closeables.closeQuietly(yarnClient); 1814 } catch (Exception ex) { 1815 LOG.error("Error when cleaning up action dir", ex); 1816 throw convertException(ex); 1817 } 1818 } 1819 } 1820 1821 private String getActionYarnTag(Context context, WorkflowAction action) { 1822 return LauncherHelper.getActionYarnTag(context.getProtoActionConf(), context.getWorkflow().getParentId(), action); 1823 } 1824 1825 private static Set<String> FINAL_STATUS = new HashSet<String>(); 1826 1827 static { 1828 FINAL_STATUS.add(SUCCEEDED); 1829 FINAL_STATUS.add(KILLED); 1830 FINAL_STATUS.add(FAILED); 1831 FINAL_STATUS.add(FAILED_KILLED); 1832 } 1833 1834 @Override 1835 public boolean isCompleted(String externalStatus) { 1836 return FINAL_STATUS.contains(externalStatus); 1837 } 1838 1839 1840 /** 1841 * Return the sharelib names for the action. 1842 * See {@link SharelibResolver} for details. 1843 * 1844 * @param context executor context. 1845 * @param actionXml the action xml. 1846 * @param conf action configuration. 1847 * @return the action sharelib names. 1848 */ 1849 protected String[] getShareLibNames(final Context context, final Element actionXml, Configuration conf) { 1850 final String sharelibFromConfigurationProperty = ACTION_SHARELIB_FOR + getType(); 1851 try { 1852 final String defaultShareLibName = getDefaultShareLibName(actionXml); 1853 final Configuration oozieServerConfiguration = Services.get().get(ConfigurationService.class).getConf(); 1854 final XConfiguration workflowConfiguration = getWorkflowConf(context); 1855 return new SharelibResolver(sharelibFromConfigurationProperty, conf, workflowConfiguration, 1856 oozieServerConfiguration, defaultShareLibName).resolve(); 1857 } catch (IOException ex) { 1858 throw new RuntimeException("Can't get workflow configuration: " + ex.toString(), ex); 1859 } 1860 } 1861 1862 1863 /** 1864 * Returns the default sharelib name for the action if any. 1865 * 1866 * @param actionXml the action XML fragment. 1867 * @return the sharelib name for the action, <code>NULL</code> if none. 1868 */ 1869 protected String getDefaultShareLibName(Element actionXml) { 1870 return null; 1871 } 1872 1873 public String[] getShareLibFilesForActionConf() { 1874 return null; 1875 } 1876 1877 /** 1878 * Sets some data for the action on completion 1879 * 1880 * @param context executor context 1881 * @param actionFs the FileSystem object 1882 * @throws java.io.IOException 1883 * @throws org.apache.oozie.service.HadoopAccessorException 1884 * @throws java.net.URISyntaxException 1885 */ 1886 protected void setActionCompletionData(Context context, FileSystem actionFs) throws IOException, 1887 HadoopAccessorException, URISyntaxException { 1888 } 1889 1890 private void injectJobInfo(Configuration launcherJobConf, Configuration actionConf, Context context, WorkflowAction action) { 1891 if (OozieJobInfo.isJobInfoEnabled()) { 1892 try { 1893 OozieJobInfo jobInfo = new OozieJobInfo(actionConf, context, action); 1894 String jobInfoStr = jobInfo.getJobInfo(); 1895 launcherJobConf.set(OozieJobInfo.JOB_INFO_KEY, jobInfoStr + "launcher=true"); 1896 actionConf.set(OozieJobInfo.JOB_INFO_KEY, jobInfoStr + "launcher=false"); 1897 } 1898 catch (Exception e) { 1899 // Just job info, should not impact the execution. 1900 LOG.error("Error while populating job info", e); 1901 } 1902 } 1903 } 1904 1905 @Override 1906 public boolean requiresNameNodeJobTracker() { 1907 return true; 1908 } 1909 1910 @Override 1911 public boolean supportsConfigurationJobXML() { 1912 return true; 1913 } 1914 1915 private XConfiguration getWorkflowConf(Context context) throws IOException { 1916 if (workflowConf == null) { 1917 workflowConf = new XConfiguration(new StringReader(context.getWorkflow().getConf())); 1918 } 1919 return workflowConf; 1920 1921 } 1922 1923 private String getActionTypeLauncherPrefix() { 1924 return "oozie.action." + getType() + ".launcher."; 1925 } 1926}