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.client; 020 021import com.fasterxml.jackson.core.type.TypeReference; 022import com.fasterxml.jackson.databind.ObjectMapper; 023import com.google.common.collect.Lists; 024import org.apache.oozie.BuildInfo; 025import org.apache.oozie.cli.ValidationUtil; 026import org.apache.oozie.client.rest.JsonTags; 027import org.apache.oozie.client.rest.JsonToBean; 028import org.apache.oozie.client.rest.RestConstants; 029import org.apache.oozie.client.retry.ConnectionRetriableClient; 030import org.json.simple.JSONArray; 031import org.json.simple.JSONObject; 032import org.json.simple.JSONValue; 033import org.w3c.dom.Document; 034import org.w3c.dom.Element; 035 036import javax.xml.parsers.DocumentBuilderFactory; 037import javax.xml.transform.Transformer; 038import javax.xml.transform.TransformerFactory; 039import javax.xml.transform.dom.DOMSource; 040import javax.xml.transform.stream.StreamResult; 041 042import java.io.BufferedReader; 043import java.io.File; 044import java.io.FileInputStream; 045import java.io.IOException; 046import java.io.InputStream; 047import java.io.InputStreamReader; 048import java.io.OutputStream; 049import java.io.PrintStream; 050import java.io.Reader; 051import java.net.HttpURLConnection; 052import java.net.URL; 053import java.net.URLEncoder; 054import java.nio.charset.StandardCharsets; 055import java.util.Collections; 056import java.util.HashMap; 057import java.util.HashSet; 058import java.util.Iterator; 059import java.util.LinkedHashMap; 060import java.util.List; 061import java.util.Map; 062import java.util.Map.Entry; 063import java.util.Properties; 064import java.util.Set; 065import java.util.concurrent.Callable; 066 067 068/** 069 * Client API to submit and manage Oozie workflow jobs against an Oozie instance. 070 * <p> 071 * This class is thread safe. 072 * <p> 073 * Syntax for filter for the {@link #getJobsInfo(String)} {@link #getJobsInfo(String, int, int)} methods: 074 * <code>[NAME=VALUE][;NAME=VALUE]*</code>. 075 * <p> 076 * Valid filter names are: 077 * <ul> 078 * <li>name: the workflow application name from the workflow definition.</li> 079 * <li>user: the user that submitted the job.</li> 080 * <li>group: the group for the job.</li> 081 * <li>status: the status of the job.</li> 082 * </ul> 083 * <p> 084 * The query will do an AND among all the filter names. The query will do an OR among all the filter values for the same 085 * name. Multiple values must be specified as different name value pairs. 086 */ 087public class OozieClient { 088 089 public static final long WS_PROTOCOL_VERSION_0 = 0; 090 091 public static final long WS_PROTOCOL_VERSION_1 = 1; 092 093 public static final long WS_PROTOCOL_VERSION = 2; // pointer to current version 094 095 public static final String USER_NAME = "user.name"; 096 097 @Deprecated 098 public static final String GROUP_NAME = "group.name"; 099 100 public static final String JOB_ACL = "oozie.job.acl"; 101 102 public static final String APP_PATH = "oozie.wf.application.path"; 103 104 public static final String COORDINATOR_APP_PATH = "oozie.coord.application.path"; 105 106 public static final String BUNDLE_APP_PATH = "oozie.bundle.application.path"; 107 108 public static final String BUNDLE_ID = "oozie.bundle.id"; 109 110 public static final String EXTERNAL_ID = "oozie.wf.external.id"; 111 112 public static final String WORKFLOW_NOTIFICATION_PROXY = "oozie.wf.workflow.notification.proxy"; 113 114 public static final String WORKFLOW_NOTIFICATION_URL = "oozie.wf.workflow.notification.url"; 115 116 public static final String ACTION_NOTIFICATION_URL = "oozie.wf.action.notification.url"; 117 118 public static final String COORD_ACTION_NOTIFICATION_URL = "oozie.coord.action.notification.url"; 119 120 public static final String COORD_ACTION_NOTIFICATION_PROXY = "oozie.coord.action.notification.proxy"; 121 122 public static final String RERUN_SKIP_NODES = "oozie.wf.rerun.skip.nodes"; 123 124 public static final String RERUN_FAIL_NODES = "oozie.wf.rerun.failnodes"; 125 126 public static final String LOG_TOKEN = "oozie.wf.log.token"; 127 128 public static final String ACTION_MAX_RETRIES = "oozie.wf.action.max.retries"; 129 130 public static final String ACTION_RETRY_INTERVAL = "oozie.wf.action.retry.interval"; 131 132 public static final String FILTER_USER = "user"; 133 134 public static final String FILTER_TEXT = "text"; 135 136 public static final String FILTER_GROUP = "group"; 137 138 public static final String FILTER_NAME = "name"; 139 140 public static final String FILTER_STATUS = "status"; 141 142 public static final String FILTER_NOMINAL_TIME = "nominaltime"; 143 144 public static final String FILTER_FREQUENCY = "frequency"; 145 146 public static final String FILTER_ID = "id"; 147 148 public static final String FILTER_UNIT = "unit"; 149 150 public static final String FILTER_JOBID = "jobid"; 151 152 public static final String FILTER_APPNAME = "appname"; 153 154 public static final String FILTER_CREATED_TIME_START = "startcreatedtime"; 155 156 public static final String FILTER_CREATED_TIME_END = "endcreatedtime"; 157 158 public static final String SLA_DISABLE_ALERT = "oozie.sla.disable.alerts"; 159 160 public static final String SLA_ENABLE_ALERT = "oozie.sla.enable.alerts"; 161 162 public static final String SLA_DISABLE_ALERT_OLDER_THAN = SLA_DISABLE_ALERT + ".older.than"; 163 164 public static final String SLA_DISABLE_ALERT_COORD = SLA_DISABLE_ALERT + ".coord"; 165 166 public static final String CHANGE_VALUE_ENDTIME = "endtime"; 167 168 public static final String CHANGE_VALUE_PAUSETIME = "pausetime"; 169 170 public static final String CHANGE_VALUE_CONCURRENCY = "concurrency"; 171 172 public static final String CHANGE_VALUE_STATUS = "status"; 173 174 public static final String LIBPATH = "oozie.libpath"; 175 176 public static final String USE_SYSTEM_LIBPATH = "oozie.use.system.libpath"; 177 178 public static final String OOZIE_SUSPEND_ON_NODES = "oozie.suspend.on.nodes"; 179 180 public static final String FILTER_SORT_BY = "sortby"; 181 182 public enum SORT_BY { 183 createdTime("createdTimestamp"), lastModifiedTime("lastModifiedTimestamp"); 184 private final String fullname; 185 186 SORT_BY(String fullname) { 187 this.fullname = fullname; 188 } 189 190 public String getFullname() { 191 return fullname; 192 } 193 } 194 195 public static enum SYSTEM_MODE { 196 NORMAL, NOWEBSERVICE, SAFEMODE 197 } 198 199 private static final Set<String> COMPLETED_WF_STATUSES = new HashSet<>(); 200 private static final Set<String> COMPLETED_COORD_AND_BUNDLE_STATUSES = new HashSet<>(); 201 private static final Set<String> COMPLETED_COORD_ACTION_STATUSES = new HashSet<>(); 202 static { 203 COMPLETED_WF_STATUSES.add(WorkflowJob.Status.FAILED.toString()); 204 COMPLETED_WF_STATUSES.add(WorkflowJob.Status.KILLED.toString()); 205 COMPLETED_WF_STATUSES.add(WorkflowJob.Status.SUCCEEDED.toString()); 206 COMPLETED_COORD_AND_BUNDLE_STATUSES.add(Job.Status.FAILED.toString()); 207 COMPLETED_COORD_AND_BUNDLE_STATUSES.add(Job.Status.KILLED.toString()); 208 COMPLETED_COORD_AND_BUNDLE_STATUSES.add(Job.Status.SUCCEEDED.toString()); 209 COMPLETED_COORD_AND_BUNDLE_STATUSES.add(Job.Status.DONEWITHERROR.toString()); 210 COMPLETED_COORD_AND_BUNDLE_STATUSES.add(Job.Status.IGNORED.toString()); 211 COMPLETED_COORD_ACTION_STATUSES.add(CoordinatorAction.Status.FAILED.toString()); 212 COMPLETED_COORD_ACTION_STATUSES.add(CoordinatorAction.Status.IGNORED.toString()); 213 COMPLETED_COORD_ACTION_STATUSES.add(CoordinatorAction.Status.KILLED.toString()); 214 COMPLETED_COORD_ACTION_STATUSES.add(CoordinatorAction.Status.SKIPPED.toString()); 215 COMPLETED_COORD_ACTION_STATUSES.add(CoordinatorAction.Status.SUCCEEDED.toString()); 216 COMPLETED_COORD_ACTION_STATUSES.add(CoordinatorAction.Status.TIMEDOUT.toString()); 217 } 218 219 /** 220 * debugMode =0 means no debugging. 1 means debugging on. 221 */ 222 public int debugMode = 0; 223 224 private int retryCount = 4; 225 226 227 private String baseUrl; 228 private String protocolUrl; 229 private boolean validatedVersion = false; 230 private JSONArray supportedVersions; 231 private final Map<String, String> headers = new HashMap<>(); 232 233 private static final ThreadLocal<String> USER_NAME_TL = new ThreadLocal<>(); 234 235 /** 236 * Allows to impersonate other users in the Oozie server. The current user 237 * must be configured as a proxyuser in Oozie. 238 * <p> 239 * IMPORTANT: impersonation happens only with Oozie client requests done within 240 * doAs() calls. 241 * 242 * @param <T> the type of the callable 243 * @param userName user to impersonate. 244 * @param callable callable with {@link OozieClient} calls impersonating the specified user. 245 * @return any response returned by the {@link Callable#call()} method. 246 * @throws Exception thrown by the {@link Callable#call()} method. 247 */ 248 public static <T> T doAs(String userName, Callable<T> callable) throws Exception { 249 notEmpty(userName, "userName"); 250 notNull(callable, "callable"); 251 try { 252 USER_NAME_TL.set(userName); 253 return callable.call(); 254 } 255 finally { 256 USER_NAME_TL.remove(); 257 } 258 } 259 260 protected OozieClient() { 261 } 262 263 /** 264 * Create a Workflow client instance. 265 * 266 * @param oozieUrl URL of the Oozie instance it will interact with. 267 */ 268 public OozieClient(String oozieUrl) { 269 this.baseUrl = notEmpty(oozieUrl, "oozieUrl"); 270 if (!this.baseUrl.endsWith("/")) { 271 this.baseUrl += "/"; 272 } 273 } 274 275 /** 276 * Return the Oozie URL of the workflow client instance. 277 * <p> 278 * This URL is the base URL fo the Oozie system, with not protocol versioning. 279 * 280 * @return the Oozie URL of the workflow client instance. 281 */ 282 public String getOozieUrl() { 283 return baseUrl; 284 } 285 286 /** 287 * Return the Oozie URL used by the client and server for WS communications. 288 * <p> 289 * This URL is the original URL plus the versioning element path. 290 * 291 * @return the Oozie URL used by the client and server for communication. 292 * @throws OozieClientException thrown in the client and the server are not protocol compatible. 293 */ 294 public String getProtocolUrl() throws OozieClientException { 295 validateWSVersion(); 296 return protocolUrl; 297 } 298 299 /** 300 * @return current debug Mode 301 */ 302 public int getDebugMode() { 303 return debugMode; 304 } 305 306 /** 307 * Set debug mode. 308 * 309 * @param debugMode : 0 means no debugging. 1 means debugging 310 */ 311 public void setDebugMode(int debugMode) { 312 this.debugMode = debugMode; 313 } 314 315 public int getRetryCount() { 316 return retryCount; 317 } 318 319 320 public void setRetryCount(int retryCount) { 321 this.retryCount = retryCount; 322 } 323 324 private String getBaseURLForVersion(long protocolVersion) throws OozieClientException { 325 try { 326 if (supportedVersions == null) { 327 supportedVersions = getSupportedProtocolVersions(); 328 } 329 if (supportedVersions == null) { 330 throw new OozieClientException("HTTP error", "no response message"); 331 } 332 if (supportedVersions.contains(protocolVersion)) { 333 return baseUrl + "v" + protocolVersion + "/"; 334 } 335 else { 336 throw new OozieClientException(OozieClientException.UNSUPPORTED_VERSION, "Protocol version " 337 + protocolVersion + " is not supported"); 338 } 339 } 340 catch (IOException e) { 341 throw new OozieClientException(OozieClientException.IO_ERROR, e); 342 } 343 } 344 345 /** 346 * Validate that the Oozie client and server instances are protocol compatible. 347 * 348 * @throws OozieClientException thrown in the client and the server are not protocol compatible. 349 */ 350 public synchronized void validateWSVersion() throws OozieClientException { 351 if (!validatedVersion) { 352 try { 353 supportedVersions = getSupportedProtocolVersions(); 354 if (supportedVersions == null) { 355 throw new OozieClientException("HTTP error", "no response message"); 356 } 357 if (!supportedVersions.contains(WS_PROTOCOL_VERSION) 358 && !supportedVersions.contains(WS_PROTOCOL_VERSION_1) 359 && !supportedVersions.contains(WS_PROTOCOL_VERSION_0)) { 360 StringBuilder msg = new StringBuilder(); 361 msg.append("Supported version [").append(WS_PROTOCOL_VERSION) 362 .append("] or less, Unsupported versions["); 363 String separator = ""; 364 for (Object version : supportedVersions) { 365 msg.append(separator).append(version); 366 } 367 msg.append("]"); 368 throw new OozieClientException(OozieClientException.UNSUPPORTED_VERSION, msg.toString()); 369 } 370 if (supportedVersions.contains(WS_PROTOCOL_VERSION)) { 371 protocolUrl = baseUrl + "v" + WS_PROTOCOL_VERSION + "/"; 372 } 373 else if (supportedVersions.contains(WS_PROTOCOL_VERSION_1)) { 374 protocolUrl = baseUrl + "v" + WS_PROTOCOL_VERSION_1 + "/"; 375 } 376 else { 377 if (supportedVersions.contains(WS_PROTOCOL_VERSION_0)) { 378 protocolUrl = baseUrl + "v" + WS_PROTOCOL_VERSION_0 + "/"; 379 } 380 } 381 } 382 catch (IOException ex) { 383 throw new OozieClientException(OozieClientException.IO_ERROR, ex); 384 } 385 validatedVersion = true; 386 } 387 } 388 389 private JSONArray getSupportedProtocolVersions() throws IOException, OozieClientException { 390 JSONArray versions = null; 391 final URL url = new URL(baseUrl + RestConstants.VERSIONS); 392 393 HttpURLConnection conn = createRetryableConnection(url, "GET"); 394 395 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { 396 versions = (JSONArray) JSONValue.parse(new InputStreamReader(conn.getInputStream())); 397 } 398 else { 399 handleError(conn); 400 } 401 return versions; 402 } 403 404 /** 405 * Create an empty configuration with just the {@link #USER_NAME} set to the JVM user name. 406 * 407 * @return an empty configuration. 408 */ 409 public Properties createConfiguration() { 410 Properties conf = new Properties(); 411 String userName = USER_NAME_TL.get(); 412 if (userName == null) { 413 userName = System.getProperty("user.name"); 414 } 415 conf.setProperty(USER_NAME, userName); 416 return conf; 417 } 418 419 /** 420 * Set a HTTP header to be used in the WS requests by the workflow instance. 421 * 422 * @param name header name. 423 * @param value header value. 424 */ 425 public void setHeader(String name, String value) { 426 headers.put(notEmpty(name, "name"), notNull(value, "value")); 427 } 428 429 /** 430 * Get the value of a set HTTP header from the workflow instance. 431 * 432 * @param name header name. 433 * @return header value, <code>null</code> if not set. 434 */ 435 public String getHeader(String name) { 436 return headers.get(notEmpty(name, "name")); 437 } 438 439 /** 440 * Get the set HTTP header 441 * 442 * @return map of header key and value 443 */ 444 public Map<String, String> getHeaders() { 445 return headers; 446 } 447 448 /** 449 * Remove a HTTP header from the workflow client instance. 450 * 451 * @param name header name. 452 */ 453 public void removeHeader(String name) { 454 headers.remove(notEmpty(name, "name")); 455 } 456 457 /** 458 * Return an iterator with all the header names set in the workflow instance. 459 * 460 * @return header names. 461 */ 462 public Iterator<String> getHeaderNames() { 463 return Collections.unmodifiableMap(headers).keySet().iterator(); 464 } 465 466 private URL createURL(Long protocolVersion, String collection, String resource, Map<String, String> parameters) 467 throws IOException, OozieClientException { 468 validateWSVersion(); 469 StringBuilder sb = new StringBuilder(); 470 if (protocolVersion == null) { 471 sb.append(protocolUrl); 472 } 473 else { 474 sb.append(getBaseURLForVersion(protocolVersion)); 475 } 476 sb.append(collection); 477 if (resource != null && resource.length() > 0) { 478 sb.append("/").append(resource); 479 } 480 if (parameters.size() > 0) { 481 String separator = "?"; 482 for (Map.Entry<String, String> param : parameters.entrySet()) { 483 if (param.getValue() != null) { 484 sb.append(separator).append(URLEncoder.encode(param.getKey(), "UTF-8")).append("=").append( 485 URLEncoder.encode(param.getValue(), "UTF-8")); 486 separator = "&"; 487 } 488 } 489 } 490 return new URL(sb.toString()); 491 } 492 493 private boolean validateCommand(String url) { 494 { 495 if (protocolUrl.contains(baseUrl + "v0")) { 496 if (url.contains("dryrun") || url.contains("jobtype=c") || url.contains("systemmode")) { 497 return false; 498 } 499 } 500 } 501 return true; 502 } 503 /** 504 * Create retryable http connection to oozie server. 505 * 506 * @param url URL to create connection to 507 * @param method method to use - GET, POST, PUT 508 * @return connection 509 * @throws IOException in case of an exception during connection setup 510 */ 511 protected HttpURLConnection createRetryableConnection(final URL url, final String method) throws IOException { 512 return (HttpURLConnection) new ConnectionRetriableClient(getRetryCount()) { 513 @Override 514 public Object doExecute(URL url, String method) throws IOException, OozieClientException { 515 HttpURLConnection conn = createConnection(url, method); 516 return conn; 517 } 518 }.execute(url, method); 519 } 520 521 /** 522 * Create http connection to oozie server. 523 * 524 * @param url URL to create connection to 525 * @param method method to use - GET, POST, PUT 526 * @return connection 527 * @throws IOException in case of an exception during connection setup 528 * @throws OozieClientException if the connection can't be set up 529 */ 530 protected HttpURLConnection createConnection(URL url, String method) throws IOException, OozieClientException { 531 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 532 conn.setRequestMethod(method); 533 if (method.equals("POST") || method.equals("PUT")) { 534 conn.setDoOutput(true); 535 } 536 for (Map.Entry<String, String> header : headers.entrySet()) { 537 conn.setRequestProperty(header.getKey(), header.getValue()); 538 } 539 return conn; 540 } 541 542 protected abstract class ClientCallable<T> implements Callable<T> { 543 private final String method; 544 private final String collection; 545 private final String resource; 546 private final Map<String, String> params; 547 private final Long protocolVersion; 548 549 public ClientCallable(String method, String collection, String resource, Map<String, String> params) { 550 this(method, null, collection, resource, params); 551 } 552 553 public ClientCallable(String method, Long protocolVersion, String collection, String resource, Map<String, String> params) { 554 this.method = method; 555 this.protocolVersion = protocolVersion; 556 this.collection = collection; 557 this.resource = resource; 558 this.params = params; 559 } 560 561 public T call() throws OozieClientException { 562 try { 563 URL url = createURL(protocolVersion, collection, resource, params); 564 if (validateCommand(url.toString())) { 565 if (getDebugMode() > 0) { 566 System.out.println(method + " " + url); 567 } 568 return call(createRetryableConnection(url, method)); 569 } 570 else { 571 System.out.println("Option not supported in target server. Supported only on Oozie-2.0 or greater." 572 + " Use 'oozie help' for details"); 573 throw new OozieClientException(OozieClientException.UNSUPPORTED_VERSION, new Exception()); 574 } 575 } 576 catch (IOException ex) { 577 throw new OozieClientException(OozieClientException.IO_ERROR, ex); 578 } 579 } 580 581 protected abstract T call(HttpURLConnection conn) throws IOException, OozieClientException; 582 583 } 584 585 protected abstract class MapClientCallable extends ClientCallable<Map<String, String>> { 586 587 MapClientCallable(String method, String collection, String resource, Map<String, String> params) { 588 super(method, collection, resource, params); 589 } 590 591 @Override 592 protected Map<String, String> call(HttpURLConnection conn) throws IOException, OozieClientException { 593 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 594 Reader reader = new InputStreamReader(conn.getInputStream()); 595 JSONObject json = (JSONObject) JSONValue.parse(reader); 596 Map<String, String> map = new HashMap<>(); 597 for (Object key : json.keySet()) { 598 map.put((String)key, (String)json.get(key)); 599 } 600 return map; 601 } 602 else { 603 handleError(conn); 604 } 605 return null; 606 } 607 } 608 609 static void handleError(HttpURLConnection conn) throws IOException, OozieClientException { 610 int status = conn.getResponseCode(); 611 String error = conn.getHeaderField(RestConstants.OOZIE_ERROR_CODE); 612 String message = conn.getHeaderField(RestConstants.OOZIE_ERROR_MESSAGE); 613 614 if (error == null) { 615 error = "HTTP error code: " + status; 616 } 617 618 if (message == null) { 619 message = conn.getResponseMessage(); 620 } 621 throw new OozieClientException(error, message); 622 } 623 624 static Map<String, String> prepareParams(String... params) { 625 Map<String, String> map = new LinkedHashMap<>(); 626 for (int i = 0; i < params.length; i = i + 2) { 627 map.put(params[i], params[i + 1]); 628 } 629 String doAsUserName = USER_NAME_TL.get(); 630 if (doAsUserName != null) { 631 map.put(RestConstants.DO_AS_PARAM, doAsUserName); 632 } 633 return map; 634 } 635 636 public void writeToXml(Properties props, OutputStream out) throws IOException { 637 try { 638 Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); 639 Element conf = doc.createElement("configuration"); 640 doc.appendChild(conf); 641 conf.appendChild(doc.createTextNode("\n")); 642 for (String name : props.stringPropertyNames()) { // Properties whose key or value is not of type String are omitted. 643 String value = props.getProperty(name); 644 Element propNode = doc.createElement("property"); 645 conf.appendChild(propNode); 646 647 Element nameNode = doc.createElement("name"); 648 nameNode.appendChild(doc.createTextNode(name.trim())); 649 propNode.appendChild(nameNode); 650 651 Element valueNode = doc.createElement("value"); 652 valueNode.appendChild(doc.createTextNode(value.trim())); 653 propNode.appendChild(valueNode); 654 655 conf.appendChild(doc.createTextNode("\n")); 656 } 657 658 DOMSource source = new DOMSource(doc); 659 StreamResult result = new StreamResult(out); 660 TransformerFactory transFactory = TransformerFactory.newInstance(); 661 transFactory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true); 662 Transformer transformer = transFactory.newTransformer(); 663 transformer.transform(source, result); 664 if (getDebugMode() > 0) { 665 result = new StreamResult(System.out); 666 transformer.transform(source, result); 667 System.out.println(); 668 } 669 } 670 catch (Exception e) { 671 throw new IOException(e); 672 } 673 } 674 675 private class JobSubmit extends ClientCallable<String> { 676 private final Properties conf; 677 678 JobSubmit(Properties conf, boolean start) { 679 super("POST", RestConstants.JOBS, "", (start) ? prepareParams(RestConstants.ACTION_PARAM, 680 RestConstants.JOB_ACTION_START) : prepareParams()); 681 this.conf = notNull(conf, "conf"); 682 } 683 684 JobSubmit(String jobId, Properties conf) { 685 super("PUT", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.ACTION_PARAM, 686 RestConstants.JOB_ACTION_RERUN)); 687 this.conf = notNull(conf, "conf"); 688 } 689 690 public JobSubmit(Properties conf, String jobActionDryrun) { 691 super("POST", RestConstants.JOBS, "", prepareParams(RestConstants.ACTION_PARAM, 692 RestConstants.JOB_ACTION_DRYRUN)); 693 this.conf = notNull(conf, "conf"); 694 } 695 696 @Override 697 protected String call(HttpURLConnection conn) throws IOException, OozieClientException { 698 conn.setRequestProperty("content-type", RestConstants.XML_CONTENT_TYPE); 699 writeToXml(conf, conn.getOutputStream()); 700 if (conn.getResponseCode() == HttpURLConnection.HTTP_CREATED) { 701 JSONObject json = (JSONObject) JSONValue.parse(new InputStreamReader(conn.getInputStream())); 702 return (String) json.get(JsonTags.JOB_ID); 703 } 704 if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { 705 handleError(conn); 706 } 707 return null; 708 } 709 } 710 711 /** 712 * Submit a workflow job. 713 * 714 * @param conf job configuration. 715 * @return the job Id. 716 * @throws OozieClientException thrown if the job could not be submitted. 717 */ 718 public String submit(Properties conf) throws OozieClientException { 719 return (new JobSubmit(conf, false)).call(); 720 } 721 722 private class JobAction extends ClientCallable<Void> { 723 724 JobAction(String jobId, String action) { 725 super("PUT", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.ACTION_PARAM, action)); 726 } 727 728 JobAction(String jobId, String action, String params) { 729 super("PUT", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.ACTION_PARAM, action, 730 RestConstants.JOB_CHANGE_VALUE, params)); 731 } 732 733 @Override 734 protected Void call(HttpURLConnection conn) throws IOException, OozieClientException { 735 if (!(conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 736 handleError(conn); 737 } 738 return null; 739 } 740 } 741 742 private class JobsAction extends ClientCallable<JSONObject> { 743 744 JobsAction(String action, String filter, String jobType, int start, int len) { 745 super("PUT", RestConstants.JOBS, "", 746 prepareParams(RestConstants.ACTION_PARAM, action, 747 RestConstants.JOB_FILTER_PARAM, filter, RestConstants.JOBTYPE_PARAM, jobType, 748 RestConstants.OFFSET_PARAM, Integer.toString(start), 749 RestConstants.LEN_PARAM, Integer.toString(len))); 750 } 751 752 @Override 753 protected JSONObject call(HttpURLConnection conn) throws IOException, OozieClientException { 754 conn.setRequestProperty("content-type", RestConstants.XML_CONTENT_TYPE); 755 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 756 Reader reader = new InputStreamReader(conn.getInputStream()); 757 JSONObject json = (JSONObject) JSONValue.parse(reader); 758 return json; 759 } 760 else { 761 handleError(conn); 762 } 763 return null; 764 } 765 } 766 /** 767 * Update coord definition. 768 * 769 * @param jobId the job id 770 * @param conf the conf 771 * @param dryrun the dryrun 772 * @param showDiff the show diff 773 * @return the string 774 * @throws OozieClientException the oozie client exception 775 */ 776 public String updateCoord(String jobId, Properties conf, String dryrun, String showDiff) 777 throws OozieClientException { 778 return (new UpdateCoord(jobId, conf, dryrun, showDiff)).call(); 779 } 780 781 /** 782 * Update coord definition without properties. 783 * 784 * @param jobId the job id 785 * @param dryrun the dryrun 786 * @param showDiff the show diff 787 * @return the string 788 * @throws OozieClientException the oozie client exception 789 */ 790 public String updateCoord(String jobId, String dryrun, String showDiff) throws OozieClientException { 791 return (new UpdateCoord(jobId, dryrun, showDiff)).call(); 792 } 793 794 /** 795 * The Class UpdateCoord. 796 */ 797 private class UpdateCoord extends ClientCallable<String> { 798 private final Properties conf; 799 800 public UpdateCoord(String jobId, Properties conf, String jobActionDryrun, String showDiff) { 801 super("PUT", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.ACTION_PARAM, 802 RestConstants.JOB_COORD_UPDATE, RestConstants.JOB_ACTION_DRYRUN, jobActionDryrun, 803 RestConstants.JOB_ACTION_SHOWDIFF, showDiff)); 804 this.conf = conf; 805 } 806 807 public UpdateCoord(String jobId, String jobActionDryrun, String showDiff) { 808 this(jobId, new Properties(), jobActionDryrun, showDiff); 809 } 810 811 @Override 812 protected String call(HttpURLConnection conn) throws IOException, OozieClientException { 813 conn.setRequestProperty("content-type", RestConstants.XML_CONTENT_TYPE); 814 writeToXml(conf, conn.getOutputStream()); 815 816 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { 817 JSONObject json = (JSONObject) JSONValue.parse(new InputStreamReader(conn.getInputStream())); 818 JSONObject update = (JSONObject) json.get(JsonTags.COORD_UPDATE); 819 if (update != null) { 820 return (String) update.get(JsonTags.COORD_UPDATE_DIFF); 821 } 822 else { 823 return ""; 824 } 825 } 826 if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { 827 handleError(conn); 828 } 829 return null; 830 } 831 } 832 833 /** 834 * dryrun for a given job 835 * 836 * @param conf Job configuration. 837 * @return new job. 838 * @throws org.apache.oozie.client.OozieClientException thrown if the job could not be submitted. 839 */ 840 public String dryrun(Properties conf) throws OozieClientException { 841 return new JobSubmit(conf, RestConstants.JOB_ACTION_DRYRUN).call(); 842 } 843 844 /** 845 * Start a workflow job. 846 * 847 * @param jobId job Id. 848 * @throws OozieClientException thrown if the job could not be started. 849 */ 850 public void start(String jobId) throws OozieClientException { 851 new JobAction(jobId, RestConstants.JOB_ACTION_START).call(); 852 } 853 854 /** 855 * Submit and start a workflow job. 856 * 857 * @param conf job configuration. 858 * @return the job Id. 859 * @throws OozieClientException thrown if the job could not be submitted. 860 */ 861 public String run(Properties conf) throws OozieClientException { 862 return (new JobSubmit(conf, true)).call(); 863 } 864 865 /** 866 * Rerun a workflow job. 867 * 868 * @param jobId job Id to rerun. 869 * @param conf configuration information for the rerun. 870 * @throws OozieClientException thrown if the job could not be started. 871 */ 872 public void reRun(String jobId, Properties conf) throws OozieClientException { 873 new JobSubmit(jobId, conf).call(); 874 } 875 876 /** 877 * Suspend a workflow job. 878 * 879 * @param jobId job Id. 880 * @throws OozieClientException thrown if the job could not be suspended. 881 */ 882 public void suspend(String jobId) throws OozieClientException { 883 new JobAction(jobId, RestConstants.JOB_ACTION_SUSPEND).call(); 884 } 885 886 /** 887 * Resume a workflow job. 888 * 889 * @param jobId job Id. 890 * @throws OozieClientException thrown if the job could not be resume. 891 */ 892 public void resume(String jobId) throws OozieClientException { 893 new JobAction(jobId, RestConstants.JOB_ACTION_RESUME).call(); 894 } 895 896 /** 897 * Kill a workflow/coord/bundle job. 898 * 899 * @param jobId job Id. 900 * @throws OozieClientException thrown if the job could not be killed. 901 */ 902 public void kill(String jobId) throws OozieClientException { 903 new JobAction(jobId, RestConstants.JOB_ACTION_KILL).call(); 904 } 905 906 /** 907 * Kill coordinator actions 908 * @param jobId coordinator Job Id 909 * @param rangeType type 'date' if -date is used, 'action-num' if -action is used 910 * @param scope kill scope for date or action nums 911 * @return list of coordinator actions that underwent kill 912 * @throws OozieClientException thrown if some actions could not be killed. 913 */ 914 public List<CoordinatorAction> kill(String jobId, String rangeType, String scope) throws OozieClientException { 915 return new CoordActionsKill(jobId, rangeType, scope).call(); 916 } 917 918 public JSONObject bulkModifyJobs(String actionType, String filter, String jobType, int start, int len) 919 throws OozieClientException { 920 return new JobsAction(actionType, filter, jobType, start, len).call(); 921 } 922 923 public JSONObject killJobs(String filter, String jobType, int start, int len) 924 throws OozieClientException { 925 return bulkModifyJobs("kill", filter, jobType, start, len); 926 } 927 928 public JSONObject suspendJobs(String filter, String jobType, int start, int len) 929 throws OozieClientException { 930 return bulkModifyJobs("suspend", filter, jobType, start, len); 931 } 932 933 public JSONObject resumeJobs(String filter, String jobType, int start, int len) 934 throws OozieClientException { 935 return bulkModifyJobs("resume", filter, jobType, start, len); 936 } 937 /** 938 * Change a coordinator job. 939 * 940 * @param jobId job Id. 941 * @param changeValue change value. 942 * @throws OozieClientException thrown if the job could not be changed. 943 */ 944 public void change(String jobId, String changeValue) throws OozieClientException { 945 new JobAction(jobId, RestConstants.JOB_ACTION_CHANGE, changeValue).call(); 946 } 947 948 /** 949 * Ignore a coordinator job. 950 * 951 * @param jobId coord job Id. 952 * @param scope list of coord actions to be ignored 953 * @return the list ignored actions or null if there are none 954 * @throws OozieClientException thrown if the job could not be changed. 955 * @return list of ignored coordinator jobs 956 */ 957 public List<CoordinatorAction> ignore(String jobId, String scope) throws OozieClientException { 958 return new CoordIgnore(jobId, RestConstants.JOB_COORD_SCOPE_ACTION, scope).call(); 959 } 960 961 private class JobInfo extends ClientCallable<WorkflowJob> { 962 963 JobInfo(String jobId, int start, int len) { 964 super("GET", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.JOB_SHOW_PARAM, 965 RestConstants.JOB_SHOW_INFO, RestConstants.OFFSET_PARAM, Integer.toString(start), 966 RestConstants.LEN_PARAM, Integer.toString(len))); 967 } 968 969 @Override 970 protected WorkflowJob call(HttpURLConnection conn) throws IOException, OozieClientException { 971 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 972 Reader reader = new InputStreamReader(conn.getInputStream()); 973 JSONObject json = (JSONObject) JSONValue.parse(reader); 974 return JsonToBean.createWorkflowJob(json); 975 } 976 else { 977 handleError(conn); 978 } 979 return null; 980 } 981 } 982 983 private class JMSInfo extends ClientCallable<JMSConnectionInfo> { 984 985 JMSInfo() { 986 super("GET", RestConstants.ADMIN, RestConstants.ADMIN_JMS_INFO, prepareParams()); 987 } 988 989 protected JMSConnectionInfo call(HttpURLConnection conn) throws IOException, OozieClientException { 990 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 991 Reader reader = new InputStreamReader(conn.getInputStream()); 992 JSONObject json = (JSONObject) JSONValue.parse(reader); 993 return JsonToBean.createJMSConnectionInfo(json); 994 } 995 else { 996 handleError(conn); 997 } 998 return null; 999 } 1000 } 1001 1002 private class WorkflowActionInfo extends ClientCallable<WorkflowAction> { 1003 WorkflowActionInfo(String actionId) { 1004 super("GET", RestConstants.JOB, notEmpty(actionId, "id"), prepareParams(RestConstants.JOB_SHOW_PARAM, 1005 RestConstants.JOB_SHOW_INFO)); 1006 } 1007 1008 @Override 1009 protected WorkflowAction call(HttpURLConnection conn) throws IOException, OozieClientException { 1010 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1011 Reader reader = new InputStreamReader(conn.getInputStream()); 1012 JSONObject json = (JSONObject) JSONValue.parse(reader); 1013 return JsonToBean.createWorkflowAction(json); 1014 } 1015 else { 1016 handleError(conn); 1017 } 1018 return null; 1019 } 1020 } 1021 1022 private class WorkflowActionRetriesInfo extends ClientCallable<List<Map<String, String>>> { 1023 WorkflowActionRetriesInfo(String actionId) { 1024 super("GET", RestConstants.JOB, notEmpty(actionId, "id"), 1025 prepareParams(RestConstants.JOB_SHOW_PARAM, RestConstants.JOB_SHOW_ACTION_RETRIES_PARAM)); 1026 } 1027 1028 @Override 1029 protected List<Map<String, String>> call(HttpURLConnection conn) 1030 throws IOException, OozieClientException { 1031 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1032 Reader reader = new InputStreamReader(conn.getInputStream()); 1033 JSONObject json = (JSONObject) JSONValue.parse(reader); 1034 return new ObjectMapper().readValue(json.get(JsonTags.WORKFLOW_ACTION_RETRIES).toString(), 1035 new TypeReference<List<Map<String, String>>>() { 1036 }); 1037 } 1038 else { 1039 handleError(conn); 1040 } 1041 return null; 1042 } 1043 } 1044 1045 /** 1046 * Get the info of a workflow job. 1047 * 1048 * @param jobId job Id. 1049 * @return the job info. 1050 * @throws OozieClientException thrown if the job info could not be retrieved. 1051 */ 1052 public WorkflowJob getJobInfo(String jobId) throws OozieClientException { 1053 return getJobInfo(jobId, 0, 0); 1054 } 1055 1056 /** 1057 * Get the JMS Connection info 1058 * @return JMSConnectionInfo object 1059 * @throws OozieClientException thrown if the JMS info could not be retrieved. 1060 */ 1061 public JMSConnectionInfo getJMSConnectionInfo() throws OozieClientException { 1062 return new JMSInfo().call(); 1063 } 1064 1065 /** 1066 * Get the info of a workflow job and subset actions. 1067 * 1068 * @param jobId job Id. 1069 * @param start starting index in the list of actions belonging to the job 1070 * @param len number of actions to be returned 1071 * @return the job info. 1072 * @throws OozieClientException thrown if the job info could not be retrieved. 1073 */ 1074 public WorkflowJob getJobInfo(String jobId, int start, int len) throws OozieClientException { 1075 return new JobInfo(jobId, start, len).call(); 1076 } 1077 1078 /** 1079 * Get the info of a workflow action. 1080 * 1081 * @param actionId Id. 1082 * @return the workflow action info. 1083 * @throws OozieClientException thrown if the job info could not be retrieved. 1084 */ 1085 public WorkflowAction getWorkflowActionInfo(String actionId) throws OozieClientException { 1086 return new WorkflowActionInfo(actionId).call(); 1087 } 1088 1089 1090 /** 1091 * Get the info of a workflow action. 1092 * 1093 * @param actionId Id. 1094 * @return the workflow action retries info. 1095 * @throws OozieClientException thrown if the job info could not be retrieved. 1096 */ 1097 public List<Map<String, String>> getWorkflowActionRetriesInfo(String actionId) throws OozieClientException { 1098 return new WorkflowActionRetriesInfo(actionId).call(); 1099 } 1100 1101 /** 1102 * Get the log of a workflow job. 1103 * 1104 * @param jobId job Id. 1105 * @return the job log. 1106 * @throws OozieClientException thrown if the job info could not be retrieved. 1107 */ 1108 public String getJobLog(String jobId) throws OozieClientException { 1109 return new JobLog(jobId).call(); 1110 } 1111 1112 /** 1113 * Get the audit log of a job. 1114 * 1115 * @param jobId the id of the job 1116 * @param ps the stream to write the result into 1117 * @throws OozieClientException thrown if the job audit log could not be retrieved. 1118 */ 1119 public void getJobAuditLog(String jobId, PrintStream ps) throws OozieClientException { 1120 new JobAuditLog(jobId, ps).call(); 1121 } 1122 1123 /** 1124 * Get the log of a job. 1125 * 1126 * @param jobId job Id. 1127 * @param logRetrievalType Based on which filter criteria the log is retrieved 1128 * @param logRetrievalScope Value for the retrieval type 1129 * @param logFilter log filter 1130 * @param ps Printstream of command line interface 1131 * @throws OozieClientException thrown if the job info could not be retrieved. 1132 */ 1133 public void getJobLog(String jobId, String logRetrievalType, String logRetrievalScope, String logFilter, 1134 PrintStream ps) throws OozieClientException { 1135 new JobLog(jobId, logRetrievalType, logRetrievalScope, logFilter, ps).call(); 1136 } 1137 1138 /** 1139 * Get the error log of a job. 1140 * 1141 * @param jobId the id of the job 1142 * @param ps the stream to write the result into 1143 * @throws OozieClientException thrown if the job log could not be retrieved. 1144 */ 1145 public void getJobErrorLog(String jobId, PrintStream ps) throws OozieClientException { 1146 new JobErrorLog(jobId, ps).call(); 1147 } 1148 1149 /** 1150 * Get the log of a job. 1151 * 1152 * @param jobId job Id. 1153 * @param logRetrievalType Based on which filter criteria the log is retrieved 1154 * @param logRetrievalScope Value for the retrieval type 1155 * @param ps Printstream of command line interface 1156 * @throws OozieClientException thrown if the job info could not be retrieved. 1157 */ 1158 public void getJobLog(String jobId, String logRetrievalType, String logRetrievalScope, PrintStream ps) 1159 throws OozieClientException { 1160 getJobLog(jobId, logRetrievalType, logRetrievalScope, null, ps); 1161 } 1162 1163 private class JobLog extends JobMetadata { 1164 JobLog(String jobId) { 1165 super(jobId, RestConstants.JOB_SHOW_LOG); 1166 } 1167 JobLog(String jobId, String logRetrievalType, String logRetrievalScope, String logFilter, PrintStream ps) { 1168 super(jobId, logRetrievalType, logRetrievalScope, RestConstants.JOB_SHOW_LOG, logFilter, ps); 1169 } 1170 } 1171 1172 private class JobErrorLog extends JobMetadata { 1173 JobErrorLog(String jobId, PrintStream ps) { 1174 super(jobId, RestConstants.JOB_SHOW_ERROR_LOG, ps); 1175 } 1176 } 1177 1178 private class JobAuditLog extends JobMetadata { 1179 JobAuditLog(String jobId, PrintStream ps) { 1180 super(jobId, RestConstants.JOB_SHOW_AUDIT_LOG, ps); 1181 } 1182 } 1183 1184 1185 /** 1186 * Gets the JMS topic name for a particular job 1187 * @param jobId given jobId 1188 * @return the JMS topic name 1189 * @throws OozieClientException thrown if the JMS topic could not be retrieved. 1190 */ 1191 public String getJMSTopicName(String jobId) throws OozieClientException { 1192 return new JMSTopic(jobId).call(); 1193 } 1194 1195 private class JMSTopic extends ClientCallable<String> { 1196 1197 JMSTopic(String jobId) { 1198 super("GET", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.JOB_SHOW_PARAM, 1199 RestConstants.JOB_SHOW_JMS_TOPIC)); 1200 } 1201 1202 protected String call(HttpURLConnection conn) throws IOException, OozieClientException { 1203 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1204 Reader reader = new InputStreamReader(conn.getInputStream()); 1205 JSONObject json = (JSONObject) JSONValue.parse(reader); 1206 return (String) json.get(JsonTags.JMS_TOPIC_NAME); 1207 } 1208 else { 1209 handleError(conn); 1210 } 1211 return null; 1212 } 1213 } 1214 1215 /** 1216 * Get the definition of a workflow job. 1217 * 1218 * @param jobId job Id. 1219 * @return the job log. 1220 * @throws OozieClientException thrown if the job info could not be retrieved. 1221 */ 1222 public String getJobDefinition(String jobId) throws OozieClientException { 1223 return new JobDefinition(jobId).call(); 1224 } 1225 1226 /** 1227 * Get coord action missing dependencies 1228 * @param jobId the id of the job 1229 * @param actionList the list of coordinator actions 1230 * @param dates a comma-separated list of date ranges. Each date range element is specified with two dates separated by '::' 1231 * @param ps the stream to write the result into 1232 * @throws OozieClientException thrown if the info could not be retrieved. 1233 */ 1234 public void getCoordActionMissingDependencies(String jobId, String actionList, String dates, PrintStream ps) 1235 throws OozieClientException { 1236 new CoordActionMissingDependencies(jobId, actionList, dates, ps).call(); 1237 } 1238 1239 /** 1240 * Get coord action missing dependencies 1241 * @param jobId the id of the job 1242 * @param actionList the list of coordinator actions 1243 * @param dates a comma-separated list of date ranges. Each date range element is specified with two dates separated by '::' 1244 * @throws OozieClientException thrown if the info could not be retrieved. 1245 */ 1246 public void getCoordActionMissingDependencies(String jobId, String actionList, String dates) 1247 throws OozieClientException { 1248 new CoordActionMissingDependencies(jobId, actionList, dates).call(); 1249 } 1250 1251 private class CoordActionMissingDependencies extends ClientCallable<String> { 1252 PrintStream printStream; 1253 public CoordActionMissingDependencies(String jobId, String actionList, String dates, PrintStream ps) { 1254 super("GET", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.JOB_SHOW_PARAM, 1255 RestConstants.COORD_ACTION_MISSING_DEPENDENCIES, RestConstants.JOB_COORD_SCOPE_ACTION_LIST, actionList, 1256 RestConstants.JOB_COORD_SCOPE_DATE, dates)); 1257 this.printStream = ps; 1258 } 1259 1260 public CoordActionMissingDependencies(String jobId, String actionList, String dates) { 1261 this(jobId, actionList, dates, System.out); 1262 } 1263 1264 1265 @SuppressWarnings("unchecked") 1266 protected String call(HttpURLConnection conn) throws IOException, OozieClientException { 1267 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1268 Reader reader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); 1269 JSONObject json = (JSONObject) JSONValue.parse(reader); 1270 if (json != null) { 1271 JSONArray inputDependencies = (JSONArray) json.get(JsonTags.COORD_ACTION_MISSING_DEPENDENCIES); 1272 for (Object dependencies : inputDependencies) { 1273 printStream.println(); 1274 printStream.println("CoordAction : " 1275 + ((JSONObject) dependencies).get(JsonTags.COORDINATOR_ACTION_ID)); 1276 if (((JSONObject) dependencies).get(JsonTags.COORD_ACTION_FIRST_MISSING_DEPENDENCIES) != null) { 1277 printStream.println("Blocked on : " 1278 + ((JSONObject) dependencies) 1279 .get(JsonTags.COORD_ACTION_FIRST_MISSING_DEPENDENCIES)); 1280 } 1281 1282 if (((JSONObject) dependencies).get(JsonTags.COORDINATOR_ACTION_DATASETS) != null) { 1283 1284 JSONArray missingDependencies = (JSONArray) ((JSONObject) dependencies) 1285 .get(JsonTags.COORDINATOR_ACTION_DATASETS); 1286 1287 for (Object missingDependenciesJson : missingDependencies) { 1288 1289 printStream.println("Dataset : " 1290 + ((JSONObject) missingDependenciesJson) 1291 .get(JsonTags.COORDINATOR_ACTION_DATASET)); 1292 1293 JSONArray inputDependenciesList = (JSONArray) ((JSONObject) missingDependenciesJson) 1294 .get(JsonTags.COORDINATOR_ACTION_MISSING_DEPS); 1295 printStream.println("Pending Dependencies : "); 1296 1297 if (inputDependenciesList != null) { 1298 Iterator<String> iterator = inputDependenciesList.iterator(); 1299 while (iterator.hasNext()) { 1300 printStream.println("\t " + iterator.next()); 1301 } 1302 } 1303 printStream.println(); 1304 } 1305 } 1306 } 1307 } 1308 else { 1309 printStream.println(" No missing input dependencies found"); 1310 } 1311 1312 } 1313 else { 1314 handleError(conn); 1315 } 1316 return null; 1317 } 1318 } 1319 1320 private class JobDefinition extends JobMetadata { 1321 1322 JobDefinition(String jobId) { 1323 super(jobId, RestConstants.JOB_SHOW_DEFINITION); 1324 } 1325 } 1326 1327 private class JobMetadata extends ClientCallable<String> { 1328 PrintStream printStream; 1329 1330 JobMetadata(String jobId, String metaType) { 1331 super("GET", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.JOB_SHOW_PARAM, 1332 metaType)); 1333 } 1334 1335 JobMetadata(String jobId, String metaType, PrintStream ps) { 1336 this(jobId, metaType); 1337 printStream = ps; 1338 1339 } 1340 1341 JobMetadata(String jobId, String logRetrievalType, String logRetrievalScope, String metaType, String logFilter, 1342 PrintStream ps) { 1343 super("GET", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.JOB_SHOW_PARAM, 1344 metaType, RestConstants.JOB_LOG_TYPE_PARAM, logRetrievalType, RestConstants.JOB_LOG_SCOPE_PARAM, 1345 logRetrievalScope, RestConstants.LOG_FILTER_OPTION, logFilter)); 1346 printStream = ps; 1347 } 1348 1349 @Override 1350 protected String call(HttpURLConnection conn) throws IOException, OozieClientException { 1351 String returnVal = null; 1352 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1353 InputStream is = conn.getInputStream(); 1354 InputStreamReader isr = new InputStreamReader(is); 1355 try { 1356 if (printStream != null) { 1357 sendToOutputStream(isr, -1, printStream); 1358 } 1359 else { 1360 returnVal = getReaderAsString(isr, -1); 1361 } 1362 } 1363 finally { 1364 isr.close(); 1365 } 1366 } 1367 else { 1368 handleError(conn); 1369 } 1370 return returnVal; 1371 } 1372 1373 /** 1374 * Output the log to command line interface 1375 * 1376 * @param reader reader to read into a string. 1377 * @param maxLen max content length allowed, if -1 there is no limit. 1378 * @throws IOException 1379 */ 1380 private void sendToOutputStream(Reader reader, int maxLen, PrintStream printStream) throws IOException { 1381 notNull(reader, "reader"); 1382 StringBuilder sb = new StringBuilder(); 1383 char[] buffer = new char[2048]; 1384 int read; 1385 int count = 0; 1386 int noOfCharstoFlush = 1024; 1387 while ((read = reader.read(buffer)) > -1) { 1388 count += read; 1389 if ((maxLen > -1) && (count > maxLen)) { 1390 break; 1391 } 1392 sb.append(buffer, 0, read); 1393 if (sb.length() > noOfCharstoFlush) { 1394 printStream.print(sb.toString()); 1395 sb = new StringBuilder(""); 1396 } 1397 } 1398 printStream.print(sb.toString()); 1399 } 1400 1401 /** 1402 * Return a reader as string. 1403 * <p> 1404 * 1405 * @param reader reader to read into a string. 1406 * @param maxLen max content length allowed, if -1 there is no limit. 1407 * @return the reader content. 1408 * @throws IOException thrown if the resource could not be read. 1409 */ 1410 private String getReaderAsString(Reader reader, int maxLen) throws IOException { 1411 notNull(reader, "reader"); 1412 StringBuffer sb = new StringBuffer(); 1413 char[] buffer = new char[2048]; 1414 int read; 1415 int count = 0; 1416 while ((read = reader.read(buffer)) > -1) { 1417 count += read; 1418 1419 // read up to maxLen chars; 1420 if ((maxLen > -1) && (count > maxLen)) { 1421 break; 1422 } 1423 sb.append(buffer, 0, read); 1424 } 1425 reader.close(); 1426 return sb.toString(); 1427 } 1428 } 1429 1430 private class CoordJobInfo extends ClientCallable<CoordinatorJob> { 1431 1432 CoordJobInfo(String jobId, String filter, int start, int len, String order) { 1433 super("GET", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.JOB_SHOW_PARAM, 1434 RestConstants.JOB_SHOW_INFO, RestConstants.JOB_FILTER_PARAM, filter, RestConstants.OFFSET_PARAM, 1435 Integer.toString(start), RestConstants.LEN_PARAM, Integer.toString(len), RestConstants.ORDER_PARAM, 1436 order)); 1437 } 1438 1439 @Override 1440 protected CoordinatorJob call(HttpURLConnection conn) throws IOException, OozieClientException { 1441 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1442 Reader reader = new InputStreamReader(conn.getInputStream()); 1443 JSONObject json = (JSONObject) JSONValue.parse(reader); 1444 return JsonToBean.createCoordinatorJob(json); 1445 } 1446 else { 1447 handleError(conn); 1448 } 1449 return null; 1450 } 1451 } 1452 1453 private class WfsForCoordAction extends ClientCallable<List<WorkflowJob>> { 1454 1455 WfsForCoordAction(String coordActionId) { 1456 super("GET", RestConstants.JOB, notEmpty(coordActionId, "coordActionId"), prepareParams( 1457 RestConstants.JOB_SHOW_PARAM, RestConstants.ALL_WORKFLOWS_FOR_COORD_ACTION)); 1458 } 1459 1460 @Override 1461 protected List<WorkflowJob> call(HttpURLConnection conn) throws IOException, OozieClientException { 1462 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1463 Reader reader = new InputStreamReader(conn.getInputStream()); 1464 JSONObject json = (JSONObject) JSONValue.parse(reader); 1465 JSONArray workflows = (JSONArray) json.get(JsonTags.WORKFLOWS_JOBS); 1466 if (workflows == null) { 1467 workflows = new JSONArray(); 1468 } 1469 return JsonToBean.createWorkflowJobList(workflows); 1470 } 1471 else { 1472 handleError(conn); 1473 } 1474 return null; 1475 } 1476 } 1477 1478 1479 private class BundleJobInfo extends ClientCallable<BundleJob> { 1480 1481 BundleJobInfo(String jobId) { 1482 super("GET", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.JOB_SHOW_PARAM, 1483 RestConstants.JOB_SHOW_INFO)); 1484 } 1485 1486 @Override 1487 protected BundleJob call(HttpURLConnection conn) throws IOException, OozieClientException { 1488 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1489 Reader reader = new InputStreamReader(conn.getInputStream()); 1490 JSONObject json = (JSONObject) JSONValue.parse(reader); 1491 return JsonToBean.createBundleJob(json); 1492 } 1493 else { 1494 handleError(conn); 1495 } 1496 return null; 1497 } 1498 } 1499 1500 private class CoordActionInfo extends ClientCallable<CoordinatorAction> { 1501 CoordActionInfo(String actionId) { 1502 super("GET", RestConstants.JOB, notEmpty(actionId, "id"), prepareParams(RestConstants.JOB_SHOW_PARAM, 1503 RestConstants.JOB_SHOW_INFO)); 1504 } 1505 1506 @Override 1507 protected CoordinatorAction call(HttpURLConnection conn) throws IOException, OozieClientException { 1508 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1509 Reader reader = new InputStreamReader(conn.getInputStream()); 1510 JSONObject json = (JSONObject) JSONValue.parse(reader); 1511 return JsonToBean.createCoordinatorAction(json); 1512 } 1513 else { 1514 handleError(conn); 1515 } 1516 return null; 1517 } 1518 } 1519 1520 /** 1521 * Get the info of a bundle job. 1522 * 1523 * @param jobId job Id. 1524 * @return the job info. 1525 * @throws OozieClientException thrown if the job info could not be retrieved. 1526 */ 1527 public BundleJob getBundleJobInfo(String jobId) throws OozieClientException { 1528 return new BundleJobInfo(jobId).call(); 1529 } 1530 1531 /** 1532 * Get the info of a coordinator job. 1533 * 1534 * @param jobId job Id. 1535 * @return the job info. 1536 * @throws OozieClientException thrown if the job info could not be retrieved. 1537 */ 1538 public CoordinatorJob getCoordJobInfo(String jobId) throws OozieClientException { 1539 return new CoordJobInfo(jobId, null, -1, -1, "asc").call(); 1540 } 1541 1542 /** 1543 * Get the info of a coordinator job and subset actions. 1544 * 1545 * @param jobId job Id. 1546 * @param filter filter the status filter 1547 * @param start starting index in the list of actions belonging to the job 1548 * @param len number of actions to be returned 1549 * @return the job info. 1550 * @throws OozieClientException thrown if the job info could not be retrieved. 1551 */ 1552 public CoordinatorJob getCoordJobInfo(String jobId, String filter, int start, int len) 1553 throws OozieClientException { 1554 return new CoordJobInfo(jobId, filter, start, len, "asc").call(); 1555 } 1556 1557 /** 1558 * Get the info of a coordinator job and subset actions. 1559 * 1560 * @param jobId job Id. 1561 * @param filter filter the status filter 1562 * @param start starting index in the list of actions belonging to the job 1563 * @param len number of actions to be returned 1564 * @param order order to list coord actions (e.g, desc) 1565 * @return the job info. 1566 * @throws OozieClientException thrown if the job info could not be retrieved. 1567 */ 1568 public CoordinatorJob getCoordJobInfo(String jobId, String filter, int start, int len, String order) 1569 throws OozieClientException { 1570 return new CoordJobInfo(jobId, filter, start, len, order).call(); 1571 } 1572 1573 public List<WorkflowJob> getWfsForCoordAction(String coordActionId) throws OozieClientException { 1574 return new WfsForCoordAction(coordActionId).call(); 1575 } 1576 1577 /** 1578 * Get the info of a coordinator action. 1579 * 1580 * @param actionId Id. 1581 * @return the coordinator action info. 1582 * @throws OozieClientException thrown if the job info could not be retrieved. 1583 */ 1584 public CoordinatorAction getCoordActionInfo(String actionId) throws OozieClientException { 1585 return new CoordActionInfo(actionId).call(); 1586 } 1587 1588 private class JobsStatus extends ClientCallable<List<WorkflowJob>> { 1589 1590 JobsStatus(String filter, int start, int len) { 1591 super("GET", RestConstants.JOBS, "", prepareParams(RestConstants.JOBS_FILTER_PARAM, filter, 1592 RestConstants.JOBTYPE_PARAM, "wf", RestConstants.OFFSET_PARAM, Integer.toString(start), 1593 RestConstants.LEN_PARAM, Integer.toString(len))); 1594 } 1595 1596 @Override 1597 protected List<WorkflowJob> call(HttpURLConnection conn) throws IOException, OozieClientException { 1598 conn.setRequestProperty("content-type", RestConstants.XML_CONTENT_TYPE); 1599 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1600 Reader reader = new InputStreamReader(conn.getInputStream()); 1601 JSONObject json = (JSONObject) JSONValue.parse(reader); 1602 JSONArray workflows = (JSONArray) json.get(JsonTags.WORKFLOWS_JOBS); 1603 if (workflows == null) { 1604 workflows = new JSONArray(); 1605 } 1606 return JsonToBean.createWorkflowJobList(workflows); 1607 } 1608 else { 1609 handleError(conn); 1610 } 1611 return null; 1612 } 1613 } 1614 1615 private class CoordJobsStatus extends ClientCallable<List<CoordinatorJob>> { 1616 1617 CoordJobsStatus(String filter, int start, int len) { 1618 super("GET", RestConstants.JOBS, "", prepareParams(RestConstants.JOBS_FILTER_PARAM, filter, 1619 RestConstants.JOBTYPE_PARAM, "coord", RestConstants.OFFSET_PARAM, Integer.toString(start), 1620 RestConstants.LEN_PARAM, Integer.toString(len))); 1621 } 1622 1623 @Override 1624 protected List<CoordinatorJob> call(HttpURLConnection conn) throws IOException, OozieClientException { 1625 conn.setRequestProperty("content-type", RestConstants.XML_CONTENT_TYPE); 1626 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1627 Reader reader = new InputStreamReader(conn.getInputStream()); 1628 JSONObject json = (JSONObject) JSONValue.parse(reader); 1629 JSONArray jobs = (JSONArray) json.get(JsonTags.COORDINATOR_JOBS); 1630 if (jobs == null) { 1631 jobs = new JSONArray(); 1632 } 1633 return JsonToBean.createCoordinatorJobList(jobs); 1634 } 1635 else { 1636 handleError(conn); 1637 } 1638 return null; 1639 } 1640 } 1641 1642 private class BundleJobsStatus extends ClientCallable<List<BundleJob>> { 1643 1644 BundleJobsStatus(String filter, int start, int len) { 1645 super("GET", RestConstants.JOBS, "", prepareParams(RestConstants.JOBS_FILTER_PARAM, filter, 1646 RestConstants.JOBTYPE_PARAM, "bundle", RestConstants.OFFSET_PARAM, Integer.toString(start), 1647 RestConstants.LEN_PARAM, Integer.toString(len))); 1648 } 1649 1650 @Override 1651 protected List<BundleJob> call(HttpURLConnection conn) throws IOException, OozieClientException { 1652 conn.setRequestProperty("content-type", RestConstants.XML_CONTENT_TYPE); 1653 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1654 Reader reader = new InputStreamReader(conn.getInputStream()); 1655 JSONObject json = (JSONObject) JSONValue.parse(reader); 1656 JSONArray jobs = (JSONArray) json.get(JsonTags.BUNDLE_JOBS); 1657 if (jobs == null) { 1658 jobs = new JSONArray(); 1659 } 1660 return JsonToBean.createBundleJobList(jobs); 1661 } 1662 else { 1663 handleError(conn); 1664 } 1665 return null; 1666 } 1667 } 1668 1669 private class BulkResponseStatus extends ClientCallable<List<BulkResponse>> { 1670 1671 BulkResponseStatus(String filter, int start, int len) { 1672 super("GET", RestConstants.JOBS, "", prepareParams(RestConstants.JOBS_BULK_PARAM, filter, 1673 RestConstants.OFFSET_PARAM, Integer.toString(start), RestConstants.LEN_PARAM, Integer.toString(len))); 1674 } 1675 1676 @Override 1677 protected List<BulkResponse> call(HttpURLConnection conn) throws IOException, OozieClientException { 1678 conn.setRequestProperty("content-type", RestConstants.XML_CONTENT_TYPE); 1679 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1680 Reader reader = new InputStreamReader(conn.getInputStream()); 1681 JSONObject json = (JSONObject) JSONValue.parse(reader); 1682 JSONArray results = (JSONArray) json.get(JsonTags.BULK_RESPONSES); 1683 if (results == null) { 1684 results = new JSONArray(); 1685 } 1686 return JsonToBean.createBulkResponseList(results); 1687 } 1688 else { 1689 handleError(conn); 1690 } 1691 return null; 1692 } 1693 } 1694 1695 private class CoordActionsKill extends ClientCallable<List<CoordinatorAction>> { 1696 1697 CoordActionsKill(String jobId, String rangeType, String scope) { 1698 super("PUT", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.ACTION_PARAM, 1699 RestConstants.JOB_ACTION_KILL, RestConstants.JOB_COORD_RANGE_TYPE_PARAM, rangeType, 1700 RestConstants.JOB_COORD_SCOPE_PARAM, scope)); 1701 } 1702 1703 @Override 1704 protected List<CoordinatorAction> call(HttpURLConnection conn) throws IOException, OozieClientException { 1705 conn.setRequestProperty("content-type", RestConstants.XML_CONTENT_TYPE); 1706 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1707 Reader reader = new InputStreamReader(conn.getInputStream()); 1708 JSONObject json = (JSONObject) JSONValue.parse(reader); 1709 JSONArray coordActions = (JSONArray) json.get(JsonTags.COORDINATOR_ACTIONS); 1710 return JsonToBean.createCoordinatorActionList(coordActions); 1711 } 1712 else { 1713 handleError(conn); 1714 } 1715 return null; 1716 } 1717 } 1718 1719 private class CoordIgnore extends ClientCallable<List<CoordinatorAction>> { 1720 CoordIgnore(String jobId, String rerunType, String scope) { 1721 super("PUT", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.ACTION_PARAM, 1722 RestConstants.JOB_ACTION_IGNORE, RestConstants.JOB_COORD_RANGE_TYPE_PARAM, 1723 rerunType, RestConstants.JOB_COORD_SCOPE_PARAM, scope)); 1724 } 1725 1726 @Override 1727 protected List<CoordinatorAction> call(HttpURLConnection conn) throws IOException, OozieClientException { 1728 conn.setRequestProperty("content-type", RestConstants.XML_CONTENT_TYPE); 1729 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1730 Reader reader = new InputStreamReader(conn.getInputStream()); 1731 JSONObject json = (JSONObject) JSONValue.parse(reader); 1732 if(json != null) { 1733 JSONArray coordActions = (JSONArray) json.get(JsonTags.COORDINATOR_ACTIONS); 1734 return JsonToBean.createCoordinatorActionList(coordActions); 1735 } 1736 } 1737 else { 1738 handleError(conn); 1739 } 1740 return null; 1741 } 1742 } 1743 private class CoordRerun extends ClientCallable<List<CoordinatorAction>> { 1744 private final Properties conf; 1745 1746 CoordRerun(String jobId, String rerunType, String scope, boolean refresh, boolean noCleanup, boolean failed, 1747 Properties conf) { 1748 super("PUT", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.ACTION_PARAM, 1749 RestConstants.JOB_COORD_ACTION_RERUN, RestConstants.JOB_COORD_RANGE_TYPE_PARAM, rerunType, 1750 RestConstants.JOB_COORD_SCOPE_PARAM, scope, RestConstants.JOB_COORD_RERUN_REFRESH_PARAM, 1751 Boolean.toString(refresh), RestConstants.JOB_COORD_RERUN_NOCLEANUP_PARAM, Boolean 1752 .toString(noCleanup), RestConstants.JOB_COORD_RERUN_FAILED_PARAM, Boolean.toString(failed))); 1753 this.conf = conf; 1754 } 1755 1756 @Override 1757 protected List<CoordinatorAction> call(HttpURLConnection conn) throws IOException, OozieClientException { 1758 conn.setRequestProperty("content-type", RestConstants.XML_CONTENT_TYPE); 1759 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1760 Reader reader = new InputStreamReader(conn.getInputStream()); 1761 JSONObject json = (JSONObject) JSONValue.parse(reader); 1762 JSONArray coordActions = (JSONArray) json.get(JsonTags.COORDINATOR_ACTIONS); 1763 return JsonToBean.createCoordinatorActionList(coordActions); 1764 } 1765 else { 1766 handleError(conn); 1767 } 1768 return null; 1769 } 1770 } 1771 1772 private class BundleRerun extends ClientCallable<Void> { 1773 1774 BundleRerun(String jobId, String coordScope, String dateScope, boolean refresh, boolean noCleanup) { 1775 super("PUT", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.ACTION_PARAM, 1776 RestConstants.JOB_BUNDLE_ACTION_RERUN, RestConstants.JOB_BUNDLE_RERUN_COORD_SCOPE_PARAM, 1777 coordScope, RestConstants.JOB_BUNDLE_RERUN_DATE_SCOPE_PARAM, dateScope, 1778 RestConstants.JOB_COORD_RERUN_REFRESH_PARAM, Boolean.toString(refresh), 1779 RestConstants.JOB_COORD_RERUN_NOCLEANUP_PARAM, Boolean.toString(noCleanup))); 1780 } 1781 1782 @Override 1783 protected Void call(HttpURLConnection conn) throws IOException, OozieClientException { 1784 conn.setRequestProperty("content-type", RestConstants.XML_CONTENT_TYPE); 1785 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 1786 return null; 1787 } 1788 else { 1789 handleError(conn); 1790 } 1791 return null; 1792 } 1793 } 1794 1795 /** 1796 * Rerun coordinator actions. 1797 * 1798 * @param jobId coordinator jobId 1799 * @param rerunType rerun type 'date' if -date is used, 'action-id' if -action is used 1800 * @param scope rerun scope for date or actionIds 1801 * @param refresh true if -refresh is given in command option 1802 * @param noCleanup true if -nocleanup is given in command option 1803 * @return the list of rerun coordinator actions 1804 * @throws OozieClientException thrown if the info could not be retrieved. 1805 */ 1806 public List<CoordinatorAction> reRunCoord(String jobId, String rerunType, String scope, boolean refresh, 1807 boolean noCleanup) throws OozieClientException { 1808 return new CoordRerun(jobId, rerunType, scope, refresh, noCleanup, false, null).call(); 1809 } 1810 1811 /** 1812 * Rerun coordinator actions with failed option. 1813 * 1814 * @param jobId coordinator jobId 1815 * @param rerunType rerun type 'date' if -date is used, 'action-id' if -action is used 1816 * @param scope rerun scope for date or actionIds 1817 * @param refresh true if -refresh is given in command option 1818 * @param noCleanup true if -nocleanup is given in command option 1819 * @param failed true if -failed is given in command option 1820 * @param props properties to use during rerun 1821 * @return new coordinator job execution 1822 * @throws OozieClientException thrown if the info could not be retrieved. 1823 */ 1824 public List<CoordinatorAction> reRunCoord(String jobId, String rerunType, String scope, boolean refresh, 1825 boolean noCleanup, boolean failed, Properties props) throws OozieClientException { 1826 return new CoordRerun(jobId, rerunType, scope, refresh, noCleanup, failed, props).call(); 1827 } 1828 1829 /** 1830 * Rerun bundle coordinators. 1831 * 1832 * @param jobId bundle jobId 1833 * @param coordScope rerun scope for coordinator jobs 1834 * @param dateScope rerun scope for date 1835 * @param refresh true if -refresh is given in command option 1836 * @param noCleanup true if -nocleanup is given in command option 1837 * @throws OozieClientException thrown if the info could not be retrieved. 1838 */ 1839 public Void reRunBundle(String jobId, String coordScope, String dateScope, boolean refresh, boolean noCleanup) 1840 throws OozieClientException { 1841 return new BundleRerun(jobId, coordScope, dateScope, refresh, noCleanup).call(); 1842 } 1843 1844 /** 1845 * Return the info of the workflow jobs that match the filter. 1846 * 1847 * @param filter job filter. Refer to the {@link OozieClient} for the filter syntax. 1848 * @param start jobs offset, base 1. 1849 * @param len number of jobs to return. 1850 * @return a list with the workflow jobs info, without node details. 1851 * @throws OozieClientException thrown if the jobs info could not be retrieved. 1852 */ 1853 public List<WorkflowJob> getJobsInfo(String filter, int start, int len) throws OozieClientException { 1854 return new JobsStatus(filter, start, len).call(); 1855 } 1856 1857 /** 1858 * Return the info of the workflow jobs that match the filter. 1859 * <p> 1860 * It returns the first 100 jobs that match the filter. 1861 * 1862 * @param filter job filter. Refer to the {@link OozieClient} for the filter syntax. 1863 * @return a list with the workflow jobs info, without node details. 1864 * @throws OozieClientException thrown if the jobs info could not be retrieved. 1865 */ 1866 public List<WorkflowJob> getJobsInfo(String filter) throws OozieClientException { 1867 return getJobsInfo(filter, 1, 50); 1868 } 1869 1870 /** 1871 * Sla enable alert. 1872 * 1873 * @param jobIds the job ids 1874 * @param actions comma separated list of action ids or action id ranges 1875 * @param dates comma separated list of the nominal times 1876 * @throws OozieClientException the oozie client exception 1877 */ 1878 public void slaEnableAlert(String jobIds, String actions, String dates) throws OozieClientException { 1879 new UpdateSLA(RestConstants.SLA_ENABLE_ALERT, jobIds, actions, dates, null).call(); 1880 } 1881 1882 /** 1883 * Sla enable alert for bundle with coord name/id. 1884 * 1885 * @param bundleId the bundle id 1886 * @param actions comma separated list of action ids or action id ranges 1887 * @param dates comma separated list of the nominal times 1888 * @param coords the coordinators 1889 * @throws OozieClientException the oozie client exception 1890 */ 1891 public void slaEnableAlert(String bundleId, String actions, String dates, String coords) 1892 throws OozieClientException { 1893 new UpdateSLA(RestConstants.SLA_ENABLE_ALERT, bundleId, actions, dates, coords).call(); 1894 } 1895 1896 /** 1897 * Sla disable alert. 1898 * 1899 * @param jobIds the job ids 1900 * @param actions comma separated list of action ids or action id ranges 1901 * @param dates comma separated list of the nominal times 1902 * @throws OozieClientException the oozie client exception 1903 */ 1904 public void slaDisableAlert(String jobIds, String actions, String dates) throws OozieClientException { 1905 new UpdateSLA(RestConstants.SLA_DISABLE_ALERT, jobIds, actions, dates, null).call(); 1906 } 1907 1908 /** 1909 * Sla disable alert for bundle with coord name/id. 1910 * 1911 * @param bundleId the bundle id 1912 * @param actions comma separated list of action ids or action id ranges 1913 * @param dates comma separated list of the nominal times 1914 * @param coords the coordinators 1915 * @throws OozieClientException the oozie client exception 1916 */ 1917 public void slaDisableAlert(String bundleId, String actions, String dates, String coords) 1918 throws OozieClientException { 1919 new UpdateSLA(RestConstants.SLA_DISABLE_ALERT, bundleId, actions, dates, coords).call(); 1920 } 1921 1922 /** 1923 * Sla change definations. 1924 * SLA change definition parameters can be [<key>=<value>,...<key>=<value>] 1925 * Supported parameter key names are should-start, should-end and max-duration 1926 * @param jobIds the job ids 1927 * @param actions comma separated list of action ids or action id ranges. 1928 * @param dates comma separated list of the nominal times 1929 * @param newSlaParams the new sla params 1930 * @throws OozieClientException the oozie client exception 1931 */ 1932 public void slaChange(String jobIds, String actions, String dates, String newSlaParams) throws OozieClientException { 1933 new UpdateSLA(RestConstants.SLA_CHANGE, jobIds, actions, dates, null, newSlaParams).call(); 1934 } 1935 1936 /** 1937 * Sla change defination for bundle with coord name/id. 1938 * SLA change definition parameters can be [<key>=<value>,...<key>=<value>] 1939 * Supported parameter key names are should-start, should-end and max-duration 1940 * @param bundleId the bundle id 1941 * @param actions comma separated list of action ids or action id ranges 1942 * @param dates comma separated list of the nominal times 1943 * @param coords the coords 1944 * @param newSlaParams the new sla params 1945 * @throws OozieClientException the oozie client exception 1946 */ 1947 public void slaChange(String bundleId, String actions, String dates, String coords, String newSlaParams) 1948 throws OozieClientException { 1949 new UpdateSLA(RestConstants.SLA_CHANGE, bundleId, actions, dates, coords, newSlaParams).call(); 1950 } 1951 1952 /** 1953 * Sla change with new sla param as hasmap. 1954 * Supported parameter key names are should-start, should-end and max-duration 1955 * @param bundleId the bundle id 1956 * @param actions comma separated list of action ids or action id ranges 1957 * @param dates comma separated list of the nominal times 1958 * @param coords the coords 1959 * @param newSlaParams the new sla params 1960 * @throws OozieClientException the oozie client exception 1961 */ 1962 public void slaChange(String bundleId, String actions, String dates, String coords, Map<String, String> newSlaParams) 1963 throws OozieClientException { 1964 new UpdateSLA(RestConstants.SLA_CHANGE, bundleId, actions, dates, coords, mapToString(newSlaParams)).call(); 1965 } 1966 1967 /** 1968 * Convert Map to string. 1969 * 1970 * @param map the map 1971 * @return the string 1972 */ 1973 protected String mapToString(Map<String, String> map) { 1974 StringBuilder sb = new StringBuilder(); 1975 Iterator<Entry<String, String>> it = map.entrySet().iterator(); 1976 while (it.hasNext()) { 1977 Entry<String, String> e = (Entry<String, String>) it.next(); 1978 sb.append(e.getKey()).append("=").append(e.getValue()).append(";"); 1979 } 1980 return sb.toString(); 1981 } 1982 1983 private class UpdateSLA extends ClientCallable<Void> { 1984 1985 UpdateSLA(String action, String jobIds, String coordActions, String dates, String coords) { 1986 super("PUT", RestConstants.JOB, notEmpty(jobIds, "jobIds"), prepareParams(RestConstants.ACTION_PARAM, 1987 action, RestConstants.JOB_COORD_SCOPE_ACTION_LIST, coordActions, RestConstants.JOB_COORD_SCOPE_DATE, 1988 dates, RestConstants.COORDINATORS_PARAM, coords)); 1989 } 1990 1991 UpdateSLA(String action, String jobIds, String coordActions, String dates, String coords, String newSlaParams) { 1992 super("PUT", RestConstants.JOB, notEmpty(jobIds, "jobIds"), prepareParams(RestConstants.ACTION_PARAM, 1993 action, RestConstants.JOB_COORD_SCOPE_ACTION_LIST, coordActions, RestConstants.JOB_COORD_SCOPE_DATE, 1994 dates, RestConstants.COORDINATORS_PARAM, coords, RestConstants.JOB_CHANGE_VALUE, newSlaParams)); 1995 } 1996 1997 @Override 1998 protected Void call(HttpURLConnection conn) throws IOException, OozieClientException { 1999 conn.setRequestProperty("content-type", RestConstants.XML_CONTENT_TYPE); 2000 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 2001 System.out.println("Done"); 2002 } 2003 else { 2004 handleError(conn); 2005 } 2006 return null; 2007 } 2008 } 2009 2010 /** 2011 * Print sla info about coordinator and workflow jobs and actions. 2012 * 2013 * @param start starting offset 2014 * @param len number of results 2015 * @param filter filters to use. Elements must be semicolon-separated name=value pairs 2016 * @throws OozieClientException thrown if the sla info could not be retrieved 2017 */ 2018 public void getSlaInfo(int start, int len, String filter) throws OozieClientException { 2019 new SlaInfo(start, len, filter).call(); 2020 } 2021 2022 private class SlaInfo extends ClientCallable<Void> { 2023 2024 SlaInfo(int start, int len, String filter) { 2025 super("GET", WS_PROTOCOL_VERSION_1, RestConstants.SLA, "", prepareParams(RestConstants.SLA_GT_SEQUENCE_ID, 2026 Integer.toString(start), RestConstants.MAX_EVENTS, Integer.toString(len), 2027 RestConstants.JOBS_FILTER_PARAM, filter)); 2028 } 2029 2030 @Override 2031 protected Void call(HttpURLConnection conn) throws IOException, OozieClientException { 2032 conn.setRequestProperty("content-type", RestConstants.XML_CONTENT_TYPE); 2033 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 2034 BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 2035 String line = null; 2036 while ((line = br.readLine()) != null) { 2037 System.out.println(line); 2038 } 2039 } 2040 else { 2041 handleError(conn); 2042 } 2043 return null; 2044 } 2045 } 2046 2047 private class JobIdAction extends ClientCallable<String> { 2048 2049 JobIdAction(String externalId) { 2050 super("GET", RestConstants.JOBS, "", prepareParams(RestConstants.JOBTYPE_PARAM, "wf", 2051 RestConstants.JOBS_EXTERNAL_ID_PARAM, externalId)); 2052 } 2053 2054 @Override 2055 protected String call(HttpURLConnection conn) throws IOException, OozieClientException { 2056 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 2057 Reader reader = new InputStreamReader(conn.getInputStream()); 2058 JSONObject json = (JSONObject) JSONValue.parse(reader); 2059 return (String) json.get(JsonTags.JOB_ID); 2060 } 2061 else { 2062 handleError(conn); 2063 } 2064 return null; 2065 } 2066 } 2067 2068 /** 2069 * Return the workflow job Id for an external Id. 2070 * <p> 2071 * The external Id must have provided at job creation time. 2072 * 2073 * @param externalId external Id given at job creation time. 2074 * @return the workflow job Id for an external Id, <code>null</code> if none. 2075 * @throws OozieClientException thrown if the operation could not be done. 2076 */ 2077 public String getJobId(String externalId) throws OozieClientException { 2078 return new JobIdAction(externalId).call(); 2079 } 2080 2081 private class SetSystemMode extends ClientCallable<Void> { 2082 2083 public SetSystemMode(SYSTEM_MODE status) { 2084 super("PUT", RestConstants.ADMIN, RestConstants.ADMIN_STATUS_RESOURCE, prepareParams( 2085 RestConstants.ADMIN_SYSTEM_MODE_PARAM, status + "")); 2086 } 2087 2088 @Override 2089 public Void call(HttpURLConnection conn) throws IOException, OozieClientException { 2090 if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { 2091 handleError(conn); 2092 } 2093 return null; 2094 } 2095 } 2096 2097 /** 2098 * Enable or disable safe mode. Used by OozieCLI. In safe mode, Oozie would not accept any commands except status 2099 * command to change and view the safe mode status. 2100 * 2101 * @param status true to enable safe mode, false to disable safe mode. 2102 * @throws OozieClientException if it fails to set the safe mode status. 2103 */ 2104 public void setSystemMode(SYSTEM_MODE status) throws OozieClientException { 2105 new SetSystemMode(status).call(); 2106 } 2107 2108 private class GetSystemMode extends ClientCallable<SYSTEM_MODE> { 2109 2110 GetSystemMode() { 2111 super("GET", RestConstants.ADMIN, RestConstants.ADMIN_STATUS_RESOURCE, prepareParams()); 2112 } 2113 2114 @Override 2115 protected SYSTEM_MODE call(HttpURLConnection conn) throws IOException, OozieClientException { 2116 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 2117 Reader reader = new InputStreamReader(conn.getInputStream()); 2118 JSONObject json = (JSONObject) JSONValue.parse(reader); 2119 return SYSTEM_MODE.valueOf((String) json.get(JsonTags.OOZIE_SYSTEM_MODE)); 2120 } 2121 else { 2122 handleError(conn); 2123 } 2124 return SYSTEM_MODE.NORMAL; 2125 } 2126 } 2127 2128 /** 2129 * Returns if Oozie is in safe mode or not. 2130 * 2131 * @return true if safe mode is ON<br> 2132 * false if safe mode is OFF 2133 * @throws OozieClientException throw if it could not obtain the safe mode status. 2134 */ 2135 /* 2136 * public boolean isInSafeMode() throws OozieClientException { return new GetSafeMode().call(); } 2137 */ 2138 public SYSTEM_MODE getSystemMode() throws OozieClientException { 2139 return new GetSystemMode().call(); 2140 } 2141 2142 public String updateShareLib() throws OozieClientException { 2143 return new UpdateSharelib().call(); 2144 } 2145 2146 public String listShareLib(String sharelibKey) throws OozieClientException { 2147 return new ListShareLib(sharelibKey).call(); 2148 } 2149 2150 private class GetBuildVersion extends ClientCallable<String> { 2151 2152 GetBuildVersion() { 2153 super("GET", RestConstants.ADMIN, RestConstants.ADMIN_BUILD_VERSION_RESOURCE, prepareParams()); 2154 } 2155 2156 @Override 2157 protected String call(HttpURLConnection conn) throws IOException, OozieClientException { 2158 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 2159 Reader reader = new InputStreamReader(conn.getInputStream()); 2160 JSONObject json = (JSONObject) JSONValue.parse(reader); 2161 return json.get(JsonTags.BUILD_INFO).toString(); 2162 } 2163 else { 2164 handleError(conn); 2165 } 2166 return null; 2167 } 2168 } 2169 2170 private class ValidateXML extends ClientCallable<String> { 2171 2172 String file = null; 2173 2174 ValidateXML(String file, String user) { 2175 super("POST", RestConstants.VALIDATE, "", 2176 prepareParams(RestConstants.FILE_PARAM, file, RestConstants.USER_PARAM, user)); 2177 this.file = file; 2178 } 2179 2180 @Override 2181 protected String call(HttpURLConnection conn) throws IOException, OozieClientException { 2182 conn.setRequestProperty("content-type", RestConstants.XML_CONTENT_TYPE); 2183 if (file.startsWith("/")) { 2184 FileInputStream fi = new FileInputStream(new File(file)); 2185 byte[] buffer = new byte[1024]; 2186 int n = 0; 2187 while (-1 != (n = fi.read(buffer))) { 2188 conn.getOutputStream().write(buffer, 0, n); 2189 } 2190 } 2191 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 2192 Reader reader = new InputStreamReader(conn.getInputStream()); 2193 JSONObject json = (JSONObject) JSONValue.parse(reader); 2194 return (String) json.get(JsonTags.VALIDATE); 2195 } 2196 else if ((conn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND)) { 2197 return null; 2198 } 2199 else { 2200 handleError(conn); 2201 } 2202 return null; 2203 } 2204 } 2205 2206 2207 private class UpdateSharelib extends ClientCallable<String> { 2208 2209 UpdateSharelib() { 2210 super("GET", RestConstants.ADMIN, RestConstants.ADMIN_UPDATE_SHARELIB, prepareParams( 2211 RestConstants.ALL_SERVER_REQUEST, "true")); 2212 } 2213 2214 @Override 2215 protected String call(HttpURLConnection conn) throws IOException, OozieClientException { 2216 StringBuffer bf = new StringBuffer(); 2217 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 2218 Reader reader = new InputStreamReader(conn.getInputStream()); 2219 Object sharelib = (Object) JSONValue.parse(reader); 2220 bf.append("[ShareLib update status]").append(System.getProperty("line.separator")); 2221 if (sharelib instanceof JSONArray) { 2222 for (Object o : ((JSONArray) sharelib)) { 2223 JSONObject obj = (JSONObject) ((JSONObject) o).get(JsonTags.SHARELIB_LIB_UPDATE); 2224 for (Object key : obj.keySet()) { 2225 bf.append("\t").append(key).append(" = ").append(obj.get(key)) 2226 .append(System.getProperty("line.separator")); 2227 } 2228 bf.append(System.getProperty("line.separator")); 2229 } 2230 } 2231 else{ 2232 JSONObject obj = (JSONObject) ((JSONObject) sharelib).get(JsonTags.SHARELIB_LIB_UPDATE); 2233 for (Object key : obj.keySet()) { 2234 bf.append("\t").append(key).append(" = ").append(obj.get(key)) 2235 .append(System.getProperty("line.separator")); 2236 } 2237 bf.append(System.getProperty("line.separator")); 2238 } 2239 return bf.toString(); 2240 } 2241 else { 2242 handleError(conn); 2243 } 2244 return null; 2245 } 2246 } 2247 2248 private class ListShareLib extends ClientCallable<String> { 2249 2250 ListShareLib(String sharelibKey) { 2251 super("GET", RestConstants.ADMIN, RestConstants.ADMIN_LIST_SHARELIB, prepareParams( 2252 RestConstants.SHARE_LIB_REQUEST_KEY, sharelibKey)); 2253 } 2254 2255 @Override 2256 protected String call(HttpURLConnection conn) throws IOException, OozieClientException { 2257 2258 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 2259 StringBuffer bf = new StringBuffer(); 2260 Reader reader = new InputStreamReader(conn.getInputStream()); 2261 JSONObject json = (JSONObject) JSONValue.parse(reader); 2262 Object sharelib = json.get(JsonTags.SHARELIB_LIB); 2263 bf.append("[Available ShareLib]").append(System.getProperty("line.separator")); 2264 if (sharelib instanceof JSONArray) { 2265 for (Object o : ((JSONArray) sharelib)) { 2266 JSONObject obj = (JSONObject) o; 2267 bf.append(obj.get(JsonTags.SHARELIB_LIB_NAME)) 2268 .append(System.getProperty("line.separator")); 2269 if (obj.get(JsonTags.SHARELIB_LIB_FILES) != null) { 2270 for (Object file : ((JSONArray) obj.get(JsonTags.SHARELIB_LIB_FILES))) { 2271 bf.append("\t").append(file).append(System.getProperty("line.separator")); 2272 } 2273 } 2274 } 2275 return bf.toString(); 2276 } 2277 } 2278 else { 2279 handleError(conn); 2280 } 2281 return null; 2282 } 2283 2284 } 2285 2286 public String purgeCommand(String purgeOptions) throws OozieClientException { 2287 String workflowAge = ""; 2288 String coordAge = ""; 2289 String bundleAge = ""; 2290 String purgeLimit = ""; 2291 String oldCoordAction = ""; 2292 if (purgeOptions != null) { 2293 String options[] = purgeOptions.split(";"); 2294 for (String option : options) { 2295 String pair[] = option.split("="); 2296 if (pair.length < 2) { 2297 throw new OozieClientException(OozieClientException.INVALID_INPUT, 2298 "Invalid purge option pair [" + option + "] specified."); 2299 } 2300 String key = pair[0].toLowerCase(); 2301 String value = pair[1]; 2302 switch (key) { 2303 case "wf": 2304 workflowAge = String.valueOf(ValidationUtil.parsePositiveInteger(value)); 2305 break; 2306 case "coord": 2307 coordAge = String.valueOf(ValidationUtil.parsePositiveInteger(value)); 2308 break; 2309 case "bundle": 2310 bundleAge = String.valueOf(ValidationUtil.parsePositiveInteger(value)); 2311 break; 2312 case "limit": 2313 purgeLimit = String.valueOf(ValidationUtil.parsePositiveInteger(value)); 2314 break; 2315 case "oldcoordaction": 2316 oldCoordAction = value; 2317 break; 2318 default: 2319 throw new OozieClientException(OozieClientException.INVALID_INPUT, 2320 "Invalid purge option [" + key + "] specified."); 2321 } 2322 } 2323 } 2324 PurgeCommand purgeCommand = new PurgeCommand(workflowAge, coordAge, bundleAge, purgeLimit, oldCoordAction); 2325 return purgeCommand.call(); 2326 } 2327 2328 private class PurgeCommand extends ClientCallable<String> { 2329 2330 PurgeCommand(String workflowAge, String coordAge, String bundleAge, String purgeLimit, String oldCoordAction) { 2331 super("PUT", RestConstants.ADMIN, RestConstants.ADMIN_PURGE, prepareParams( 2332 RestConstants.PURGE_WF_AGE, workflowAge, 2333 RestConstants.PURGE_COORD_AGE, coordAge, 2334 RestConstants.PURGE_BUNDLE_AGE, bundleAge, 2335 RestConstants.PURGE_LIMIT, purgeLimit, 2336 RestConstants.PURGE_OLD_COORD_ACTION, oldCoordAction 2337 )); 2338 } 2339 2340 @Override 2341 protected String call(HttpURLConnection conn) throws IOException, OozieClientException { 2342 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { 2343 Reader reader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); 2344 JSONObject jsonObject = (JSONObject) JSONValue.parse(reader); 2345 Object msg = jsonObject.get(JsonTags.PURGE); 2346 return msg.toString(); 2347 } else { 2348 handleError(conn); 2349 } 2350 return null; 2351 } 2352 } 2353 2354 /** 2355 * Return the Oozie server build version. 2356 * 2357 * @return the Oozie server build version. 2358 * @throws OozieClientException throw if the server build version could not be retrieved. 2359 */ 2360 public String getServerBuildVersion() throws OozieClientException { 2361 return new GetBuildVersion().call(); 2362 } 2363 2364 /** 2365 * Return the Oozie client build version. 2366 * 2367 * @return the Oozie client build version. 2368 */ 2369 public String getClientBuildVersion() { 2370 return BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_VERSION); 2371 } 2372 2373 /** 2374 * Return the workflow application is valid. 2375 * 2376 * @param file local file or hdfs file. 2377 * @return the workflow application is valid. 2378 * @throws OozieClientException throw if it the workflow application's validation could not be retrieved. 2379 */ 2380 public String validateXML(String file) throws OozieClientException { 2381 String fileName = file; 2382 if (file.startsWith("file://")) { 2383 fileName = file.substring(7, file.length()); 2384 } 2385 if (!fileName.contains("://")) { 2386 File f = new File(fileName); 2387 if (!f.isFile()) { 2388 throw new OozieClientException("File error", "File does not exist : " + f.getAbsolutePath()); 2389 } 2390 fileName = f.getAbsolutePath(); 2391 } 2392 String user = USER_NAME_TL.get(); 2393 if (user == null) { 2394 user = System.getProperty("user.name"); 2395 } 2396 return new ValidateXML(fileName, user).call(); 2397 } 2398 2399 /** 2400 * Return the info of the coordinator jobs that match the filter. 2401 * 2402 * @param filter job filter. Refer to the {@link OozieClient} for the filter syntax. 2403 * @param start jobs offset, base 1. 2404 * @param len number of jobs to return. 2405 * @return a list with the coordinator jobs info 2406 * @throws OozieClientException thrown if the jobs info could not be retrieved. 2407 */ 2408 public List<CoordinatorJob> getCoordJobsInfo(String filter, int start, int len) throws OozieClientException { 2409 return new CoordJobsStatus(filter, start, len).call(); 2410 } 2411 2412 /** 2413 * Return the info of the bundle jobs that match the filter. 2414 * 2415 * @param filter job filter. Refer to the {@link OozieClient} for the filter syntax. 2416 * @param start jobs offset, base 1. 2417 * @param len number of jobs to return. 2418 * @return a list with the bundle jobs info 2419 * @throws OozieClientException thrown if the jobs info could not be retrieved. 2420 */ 2421 public List<BundleJob> getBundleJobsInfo(String filter, int start, int len) throws OozieClientException { 2422 return new BundleJobsStatus(filter, start, len).call(); 2423 } 2424 2425 public List<BulkResponse> getBulkInfo(String filter, int start, int len) throws OozieClientException { 2426 return new BulkResponseStatus(filter, start, len).call(); 2427 } 2428 2429 /** 2430 * Poll a job (Workflow Job ID, Coordinator Job ID, Coordinator Action ID, or Bundle Job ID) and return when it has reached a 2431 * terminal state. 2432 * (i.e. FAILED, KILLED, SUCCEEDED) 2433 * 2434 * @param id The Job ID 2435 * @param timeout timeout in minutes (negative values indicate no timeout) 2436 * @param interval polling interval in minutes (must be positive) 2437 * @param verbose if true, the current status will be printed out at each poll; if false, no output 2438 * @throws OozieClientException thrown if the job's status could not be retrieved 2439 */ 2440 public void pollJob(String id, int timeout, int interval, boolean verbose) throws OozieClientException { 2441 notEmpty("id", id); 2442 if (interval < 1) { 2443 throw new IllegalArgumentException("interval must be a positive integer"); 2444 } 2445 boolean noTimeout = (timeout < 1); 2446 long endTime = System.currentTimeMillis() + timeout * 60 * 1000; 2447 interval *= 60 * 1000; 2448 2449 final Set<String> completedStatuses; 2450 if (id.endsWith("-W")) { 2451 completedStatuses = COMPLETED_WF_STATUSES; 2452 } else if (id.endsWith("-C")) { 2453 completedStatuses = COMPLETED_COORD_AND_BUNDLE_STATUSES; 2454 } else if (id.endsWith("-B")) { 2455 completedStatuses = COMPLETED_COORD_AND_BUNDLE_STATUSES; 2456 } else if (id.contains("-C@")) { 2457 completedStatuses = COMPLETED_COORD_ACTION_STATUSES; 2458 } else { 2459 throw new IllegalArgumentException("invalid job type"); 2460 } 2461 2462 String status = getStatus(id); 2463 if (verbose) { 2464 System.out.println(status); 2465 } 2466 while(!completedStatuses.contains(status) && (noTimeout || System.currentTimeMillis() <= endTime)) { 2467 try { 2468 Thread.sleep(interval); 2469 } catch (InterruptedException ie) { 2470 // ignore 2471 } 2472 status = getStatus(id); 2473 if (verbose) { 2474 System.out.println(status); 2475 } 2476 } 2477 } 2478 2479 /** 2480 * Gets the status for a particular job (Workflow Job ID, Coordinator Job ID, Coordinator Action ID, or Bundle Job ID). 2481 * 2482 * @param jobId given jobId 2483 * @return the status 2484 * @throws OozieClientException thrown if the status could not be retrieved 2485 */ 2486 public String getStatus(String jobId) throws OozieClientException { 2487 return new Status(jobId).call(); 2488 } 2489 2490 private class Status extends ClientCallable<String> { 2491 2492 Status(String jobId) { 2493 super("GET", RestConstants.JOB, notEmpty(jobId, "jobId"), prepareParams(RestConstants.JOB_SHOW_PARAM, 2494 RestConstants.JOB_SHOW_STATUS)); 2495 } 2496 2497 @Override 2498 protected String call(HttpURLConnection conn) throws IOException, OozieClientException { 2499 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 2500 Reader reader = new InputStreamReader(conn.getInputStream()); 2501 JSONObject json = (JSONObject) JSONValue.parse(reader); 2502 return (String) json.get(JsonTags.STATUS); 2503 } 2504 else { 2505 handleError(conn); 2506 } 2507 return null; 2508 } 2509 } 2510 2511 private class GetQueueDump extends ClientCallable<List<String>> { 2512 GetQueueDump() { 2513 super("GET", RestConstants.ADMIN, RestConstants.ADMIN_QUEUE_DUMP_RESOURCE, prepareParams()); 2514 } 2515 2516 @Override 2517 protected List<String> call(HttpURLConnection conn) throws IOException, OozieClientException { 2518 if ((conn.getResponseCode() != HttpURLConnection.HTTP_OK)) { 2519 handleError(conn); 2520 return null; 2521 } 2522 2523 Reader reader = new InputStreamReader(conn.getInputStream()); 2524 JSONObject json = (JSONObject) JSONValue.parse(reader); 2525 List<String> queueDumpMessages = Lists.newArrayList(); 2526 2527 addSeparator(queueDumpMessages); 2528 2529 addQueueMessages(json, 2530 queueDumpMessages, 2531 JsonTags.QUEUE_DUMP, 2532 JsonTags.CALLABLE_DUMP, 2533 "[Server Queue Dump]:", 2534 "The queue dump is empty, nothing to display."); 2535 2536 addSeparator(queueDumpMessages); 2537 2538 addQueueMessages(json, 2539 queueDumpMessages, 2540 JsonTags.UNIQUE_MAP_DUMP, 2541 JsonTags.UNIQUE_ENTRY_DUMP, 2542 "[Server Uniqueness Map Dump]:", 2543 "The uniqueness map dump is empty, nothing to display."); 2544 2545 addSeparator(queueDumpMessages); 2546 2547 return queueDumpMessages; 2548 } 2549 2550 private void addQueueMessages(JSONObject json, 2551 List<String> queueMessages, 2552 String queueName, 2553 String queueValue, 2554 String headerMessage, 2555 String emptyMessage) { 2556 2557 JSONArray queueDumpArray = (JSONArray) json.get(queueName); 2558 queueMessages.add(headerMessage); 2559 2560 for (Object o : queueDumpArray) { 2561 JSONObject entry = (JSONObject) o; 2562 if (entry.get(queueValue) != null) { 2563 String value = (String) entry.get(queueValue); 2564 queueMessages.add(value); 2565 } 2566 } 2567 2568 if (queueDumpArray.isEmpty()) { 2569 queueMessages.add(emptyMessage); 2570 } 2571 } 2572 2573 private void addSeparator(List<String> list) { 2574 list.add("******************************************"); 2575 } 2576 } 2577 2578 /** 2579 * Return the Oozie queue's commands' dump 2580 * 2581 * @return the list of strings of callable identification in queue 2582 * @throws OozieClientException throw if it the queue dump could not be retrieved. 2583 */ 2584 public List<String> getQueueDump() throws OozieClientException { 2585 return new GetQueueDump().call(); 2586 } 2587 2588 private class GetAvailableOozieServers extends MapClientCallable { 2589 2590 GetAvailableOozieServers() { 2591 super("GET", RestConstants.ADMIN, RestConstants.ADMIN_AVAILABLE_OOZIE_SERVERS_RESOURCE, prepareParams()); 2592 } 2593 } 2594 2595 /** 2596 * Return the list of available Oozie servers. 2597 * 2598 * @return the list of available Oozie servers. 2599 * @throws OozieClientException throw if it the list of available Oozie servers could not be retrieved. 2600 */ 2601 public Map<String, String> getAvailableOozieServers() throws OozieClientException { 2602 return new GetAvailableOozieServers().call(); 2603 } 2604 2605 private class GetServerConfiguration extends MapClientCallable { 2606 2607 GetServerConfiguration() { 2608 super("GET", RestConstants.ADMIN, RestConstants.ADMIN_CONFIG_RESOURCE, prepareParams()); 2609 } 2610 } 2611 2612 /** 2613 * Return the Oozie system configuration. 2614 * 2615 * @return the Oozie system configuration. 2616 * @throws OozieClientException throw if the system configuration could not be retrieved. 2617 */ 2618 public Map<String, String> getServerConfiguration() throws OozieClientException { 2619 return new GetServerConfiguration().call(); 2620 } 2621 2622 private class GetJavaSystemProperties extends MapClientCallable { 2623 2624 GetJavaSystemProperties() { 2625 super("GET", RestConstants.ADMIN, RestConstants.ADMIN_JAVA_SYS_PROPS_RESOURCE, prepareParams()); 2626 } 2627 } 2628 2629 /** 2630 * Return the Oozie Java system properties. 2631 * 2632 * @return the Oozie Java system properties. 2633 * @throws OozieClientException throw if the system properties could not be retrieved. 2634 */ 2635 public Map<String, String> getJavaSystemProperties() throws OozieClientException { 2636 return new GetJavaSystemProperties().call(); 2637 } 2638 2639 private class GetOSEnv extends MapClientCallable { 2640 2641 GetOSEnv() { 2642 super("GET", RestConstants.ADMIN, RestConstants.ADMIN_OS_ENV_RESOURCE, prepareParams()); 2643 } 2644 } 2645 2646 /** 2647 * Return the Oozie system OS environment. 2648 * 2649 * @return the Oozie system OS environment. 2650 * @throws OozieClientException throw if the system OS environment could not be retrieved. 2651 */ 2652 public Map<String, String> getOSEnv() throws OozieClientException { 2653 return new GetOSEnv().call(); 2654 } 2655 2656 private class GetMetrics extends ClientCallable<Metrics> { 2657 2658 GetMetrics() { 2659 super("GET", RestConstants.ADMIN, RestConstants.ADMIN_METRICS_RESOURCE, prepareParams()); 2660 } 2661 2662 @Override 2663 protected Metrics call(HttpURLConnection conn) throws IOException, OozieClientException { 2664 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 2665 Reader reader = new InputStreamReader(conn.getInputStream()); 2666 JSONObject json = (JSONObject) JSONValue.parse(reader); 2667 Metrics metrics = new Metrics(json); 2668 return metrics; 2669 } 2670 else if ((conn.getResponseCode() == HttpURLConnection.HTTP_UNAVAILABLE)) { 2671 // Use Instrumentation endpoint 2672 return null; 2673 } 2674 else { 2675 handleError(conn); 2676 } 2677 return null; 2678 } 2679 } 2680 2681 public class Metrics { 2682 private Map<String, Long> counters; 2683 private Map<String, Object> gauges; 2684 private Map<String, Timer> timers; 2685 private Map<String, Histogram> histograms; 2686 2687 @SuppressWarnings("unchecked") 2688 public Metrics(JSONObject json) { 2689 JSONObject jCounters = (JSONObject) json.get("counters"); 2690 counters = new HashMap<String, Long>(jCounters.size()); 2691 for (Object entO : jCounters.entrySet()) { 2692 Entry<String, JSONObject> ent = (Entry<String, JSONObject>) entO; 2693 counters.put(ent.getKey(), (Long)ent.getValue().get("count")); 2694 } 2695 2696 JSONObject jGuages = (JSONObject) json.get("gauges"); 2697 gauges = new HashMap<String, Object>(jGuages.size()); 2698 for (Object entO : jGuages.entrySet()) { 2699 Entry<String, JSONObject> ent = (Entry<String, JSONObject>) entO; 2700 gauges.put(ent.getKey(), ent.getValue().get("value")); 2701 } 2702 2703 JSONObject jTimers = (JSONObject) json.get("timers"); 2704 timers = new HashMap<String, Timer>(jTimers.size()); 2705 for (Object entO : jTimers.entrySet()) { 2706 Entry<String, JSONObject> ent = (Entry<String, JSONObject>) entO; 2707 timers.put(ent.getKey(), new Timer(ent.getValue())); 2708 } 2709 2710 JSONObject jHistograms = (JSONObject) json.get("histograms"); 2711 histograms = new HashMap<String, Histogram>(jHistograms.size()); 2712 for (Object entO : jHistograms.entrySet()) { 2713 Entry<String, JSONObject> ent = (Entry<String, JSONObject>) entO; 2714 histograms.put(ent.getKey(), new Histogram(ent.getValue())); 2715 } 2716 } 2717 2718 public Map<String, Long> getCounters() { 2719 return counters; 2720 } 2721 2722 public Map<String, Object> getGauges() { 2723 return gauges; 2724 } 2725 2726 public Map<String, Timer> getTimers() { 2727 return timers; 2728 } 2729 2730 public Map<String, Histogram> getHistograms() { 2731 return histograms; 2732 } 2733 2734 public class Timer extends Histogram { 2735 private double m15Rate; 2736 private double m5Rate; 2737 private double m1Rate; 2738 private double meanRate; 2739 private String durationUnits; 2740 private String rateUnits; 2741 2742 public Timer(JSONObject json) { 2743 super(json); 2744 m15Rate = Double.valueOf(json.get("m15_rate").toString()); 2745 m5Rate = Double.valueOf(json.get("m5_rate").toString()); 2746 m1Rate = Double.valueOf(json.get("m1_rate").toString()); 2747 meanRate = Double.valueOf(json.get("mean_rate").toString()); 2748 durationUnits = json.get("duration_units").toString(); 2749 rateUnits = json.get("rate_units").toString(); 2750 } 2751 2752 public double get15MinuteRate() { 2753 return m15Rate; 2754 } 2755 2756 public double get5MinuteRate() { 2757 return m5Rate; 2758 } 2759 2760 public double get1MinuteRate() { 2761 return m1Rate; 2762 } 2763 2764 public double getMeanRate() { 2765 return meanRate; 2766 } 2767 2768 public String getDurationUnits() { 2769 return durationUnits; 2770 } 2771 2772 public String getRateUnits() { 2773 return rateUnits; 2774 } 2775 2776 @Override 2777 public String toString() { 2778 StringBuilder sb = new StringBuilder(super.toString()); 2779 sb.append("\n\t15 minute rate : ").append(m15Rate); 2780 sb.append("\n\t5 minute rate : ").append(m5Rate); 2781 sb.append("\n\t1 minute rate : ").append(m15Rate); 2782 sb.append("\n\tmean rate : ").append(meanRate); 2783 sb.append("\n\tduration units : ").append(durationUnits); 2784 sb.append("\n\trate units : ").append(rateUnits); 2785 return sb.toString(); 2786 } 2787 } 2788 2789 public class Histogram { 2790 private double p999; 2791 private double p99; 2792 private double p98; 2793 private double p95; 2794 private double p75; 2795 private double p50; 2796 private double mean; 2797 private double min; 2798 private double max; 2799 private double stdDev; 2800 private long count; 2801 2802 public Histogram(JSONObject json) { 2803 p999 = Double.valueOf(json.get("p999").toString()); 2804 p99 = Double.valueOf(json.get("p99").toString()); 2805 p98 = Double.valueOf(json.get("p98").toString()); 2806 p95 = Double.valueOf(json.get("p95").toString()); 2807 p75 = Double.valueOf(json.get("p75").toString()); 2808 p50 = Double.valueOf(json.get("p50").toString()); 2809 mean = Double.valueOf(json.get("mean").toString()); 2810 min = Double.valueOf(json.get("min").toString()); 2811 max = Double.valueOf(json.get("max").toString()); 2812 stdDev = Double.valueOf(json.get("stddev").toString()); 2813 count = Long.valueOf(json.get("count").toString()); 2814 } 2815 2816 public double get999thPercentile() { 2817 return p999; 2818 } 2819 2820 public double get99thPercentile() { 2821 return p99; 2822 } 2823 2824 public double get98thPercentile() { 2825 return p98; 2826 } 2827 2828 public double get95thPercentile() { 2829 return p95; 2830 } 2831 2832 public double get75thPercentile() { 2833 return p75; 2834 } 2835 2836 public double get50thPercentile() { 2837 return p50; 2838 } 2839 2840 public double getMean() { 2841 return mean; 2842 } 2843 2844 public double getMin() { 2845 return min; 2846 } 2847 2848 public double getMax() { 2849 return max; 2850 } 2851 2852 public double getStandardDeviation() { 2853 return stdDev; 2854 } 2855 2856 public long getCount() { 2857 return count; 2858 } 2859 2860 @Override 2861 public String toString() { 2862 StringBuilder sb = new StringBuilder(); 2863 sb.append("\t999th percentile : ").append(p999); 2864 sb.append("\n\t99th percentile : ").append(p99); 2865 sb.append("\n\t98th percentile : ").append(p98); 2866 sb.append("\n\t95th percentile : ").append(p95); 2867 sb.append("\n\t75th percentile : ").append(p75); 2868 sb.append("\n\t50th percentile : ").append(p50); 2869 sb.append("\n\tmean : ").append(mean); 2870 sb.append("\n\tmax : ").append(max); 2871 sb.append("\n\tmin : ").append(min); 2872 sb.append("\n\tcount : ").append(count); 2873 sb.append("\n\tstandard deviation : ").append(stdDev); 2874 return sb.toString(); 2875 } 2876 } 2877 } 2878 2879 /** 2880 * Return the Oozie metrics. If null is returned, then try {@link #getInstrumentation()}. 2881 * 2882 * @return the Oozie metrics or null. 2883 * @throws OozieClientException throw if the metrics could not be retrieved. 2884 */ 2885 public Metrics getMetrics() throws OozieClientException { 2886 return new GetMetrics().call(); 2887 } 2888 2889 private class GetInstrumentation extends ClientCallable<Instrumentation> { 2890 2891 GetInstrumentation() { 2892 super("GET", RestConstants.ADMIN, RestConstants.ADMIN_INSTRUMENTATION_RESOURCE, prepareParams()); 2893 } 2894 2895 @Override 2896 protected Instrumentation call(HttpURLConnection conn) throws IOException, OozieClientException { 2897 if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { 2898 Reader reader = new InputStreamReader(conn.getInputStream()); 2899 JSONObject json = (JSONObject) JSONValue.parse(reader); 2900 Instrumentation instrumentation = new Instrumentation(json); 2901 return instrumentation; 2902 } 2903 else if ((conn.getResponseCode() == HttpURLConnection.HTTP_UNAVAILABLE)) { 2904 // Use Metrics endpoint 2905 return null; 2906 } 2907 else { 2908 handleError(conn); 2909 } 2910 return null; 2911 } 2912 } 2913 2914 public class Instrumentation { 2915 private Map<String, Long> counters; 2916 private Map<String, Object> variables; 2917 private Map<String, Double> samplers; 2918 private Map<String, Timer> timers; 2919 2920 public Instrumentation(JSONObject json) { 2921 JSONArray jCounters = (JSONArray) json.get("counters"); 2922 counters = new HashMap<String, Long>(jCounters.size()); 2923 for (Object groupO : jCounters) { 2924 JSONObject group = (JSONObject) groupO; 2925 String groupName = group.get("group").toString() + "."; 2926 JSONArray data = (JSONArray) group.get("data"); 2927 for (Object datO : data) { 2928 JSONObject dat = (JSONObject) datO; 2929 counters.put(groupName + dat.get("name").toString(), Long.valueOf(dat.get("value").toString())); 2930 } 2931 } 2932 2933 JSONArray jVariables = (JSONArray) json.get("variables"); 2934 variables = new HashMap<String, Object>(jVariables.size()); 2935 for (Object groupO : jVariables) { 2936 JSONObject group = (JSONObject) groupO; 2937 String groupName = group.get("group").toString() + "."; 2938 JSONArray data = (JSONArray) group.get("data"); 2939 for (Object datO : data) { 2940 JSONObject dat = (JSONObject) datO; 2941 variables.put(groupName + dat.get("name").toString(), dat.get("value")); 2942 } 2943 } 2944 2945 JSONArray jSamplers = (JSONArray) json.get("samplers"); 2946 samplers = new HashMap<String, Double>(jSamplers.size()); 2947 for (Object groupO : jSamplers) { 2948 JSONObject group = (JSONObject) groupO; 2949 String groupName = group.get("group").toString() + "."; 2950 JSONArray data = (JSONArray) group.get("data"); 2951 for (Object datO : data) { 2952 JSONObject dat = (JSONObject) datO; 2953 samplers.put(groupName + dat.get("name").toString(), Double.valueOf(dat.get("value").toString())); 2954 } 2955 } 2956 2957 JSONArray jTimers = (JSONArray) json.get("timers"); 2958 timers = new HashMap<String, Timer>(jTimers.size()); 2959 for (Object groupO : jTimers) { 2960 JSONObject group = (JSONObject) groupO; 2961 String groupName = group.get("group").toString() + "."; 2962 JSONArray data = (JSONArray) group.get("data"); 2963 for (Object datO : data) { 2964 JSONObject dat = (JSONObject) datO; 2965 timers.put(groupName + dat.get("name").toString(), new Timer(dat)); 2966 } 2967 } 2968 } 2969 2970 public class Timer { 2971 private double ownTimeStdDev; 2972 private long ownTimeAvg; 2973 private long ownMaxTime; 2974 private long ownMinTime; 2975 private double totalTimeStdDev; 2976 private long totalTimeAvg; 2977 private long totalMaxTime; 2978 private long totalMinTime; 2979 private long ticks; 2980 2981 public Timer(JSONObject json) { 2982 ownTimeStdDev = Double.valueOf(json.get("ownTimeStdDev").toString()); 2983 ownTimeAvg = Long.valueOf(json.get("ownTimeAvg").toString()); 2984 ownMaxTime = Long.valueOf(json.get("ownMaxTime").toString()); 2985 ownMinTime = Long.valueOf(json.get("ownMinTime").toString()); 2986 totalTimeStdDev = Double.valueOf(json.get("totalTimeStdDev").toString()); 2987 totalTimeAvg = Long.valueOf(json.get("totalTimeAvg").toString()); 2988 totalMaxTime = Long.valueOf(json.get("totalMaxTime").toString()); 2989 totalMinTime = Long.valueOf(json.get("totalMinTime").toString()); 2990 ticks = Long.valueOf(json.get("ticks").toString()); 2991 } 2992 2993 public double getOwnTimeStandardDeviation() { 2994 return ownTimeStdDev; 2995 } 2996 2997 public long getOwnTimeAverage() { 2998 return ownTimeAvg; 2999 } 3000 3001 public long getOwnMaxTime() { 3002 return ownMaxTime; 3003 } 3004 3005 public long getOwnMinTime() { 3006 return ownMinTime; 3007 } 3008 3009 public double getTotalTimeStandardDeviation() { 3010 return totalTimeStdDev; 3011 } 3012 3013 public long getTotalTimeAverage() { 3014 return totalTimeAvg; 3015 } 3016 3017 public long getTotalMaxTime() { 3018 return totalMaxTime; 3019 } 3020 3021 public long getTotalMinTime() { 3022 return totalMinTime; 3023 } 3024 3025 public long getTicks() { 3026 return ticks; 3027 } 3028 3029 @Override 3030 public String toString() { 3031 StringBuilder sb = new StringBuilder(); 3032 sb.append("\town time standard deviation : ").append(ownTimeStdDev); 3033 sb.append("\n\town average time : ").append(ownTimeAvg); 3034 sb.append("\n\town max time : ").append(ownMaxTime); 3035 sb.append("\n\town min time : ").append(ownMinTime); 3036 sb.append("\n\ttotal time standard deviation : ").append(totalTimeStdDev); 3037 sb.append("\n\ttotal average time : ").append(totalTimeAvg); 3038 sb.append("\n\ttotal max time : ").append(totalMaxTime); 3039 sb.append("\n\ttotal min time : ").append(totalMinTime); 3040 sb.append("\n\tticks : ").append(ticks); 3041 return sb.toString(); 3042 } 3043 } 3044 3045 public Map<String, Long> getCounters() { 3046 return counters; 3047 } 3048 3049 public Map<String, Object> getVariables() { 3050 return variables; 3051 } 3052 3053 public Map<String, Double> getSamplers() { 3054 return samplers; 3055 } 3056 3057 public Map<String, Timer> getTimers() { 3058 return timers; 3059 } 3060 } 3061 3062 /** 3063 * Return the Oozie instrumentation. If null is returned, then try {@link #getMetrics()}. 3064 * 3065 * @return the Oozie intstrumentation or null. 3066 * @throws OozieClientException throw if the intstrumentation could not be retrieved. 3067 */ 3068 public Instrumentation getInstrumentation() throws OozieClientException { 3069 return new GetInstrumentation().call(); 3070 } 3071 3072 /** 3073 * Check if the string is not null or not empty. 3074 * 3075 * @param str the string to check 3076 * @param name the name to present in the error message 3077 * @return string 3078 */ 3079 public static String notEmpty(String str, String name) { 3080 if (str == null) { 3081 throw new IllegalArgumentException(name + " cannot be null"); 3082 } 3083 if (str.length() == 0) { 3084 throw new IllegalArgumentException(name + " cannot be empty"); 3085 } 3086 return str; 3087 } 3088 3089 /** 3090 * Check if the object is not null. 3091 * 3092 * @param <T> the type of the object 3093 * @param obj the object to check 3094 * @param name the name to present in the error message 3095 * @return string 3096 */ 3097 public static <T> T notNull(T obj, String name) { 3098 if (obj == null) { 3099 throw new IllegalArgumentException(name + " cannot be null"); 3100 } 3101 return obj; 3102 } 3103 3104}