You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@impala.apache.org by ta...@apache.org on 2019/02/22 17:34:43 UTC

[impala] branch 2.x updated (ec2e30a -> 23922dd)

This is an automated email from the ASF dual-hosted git repository.

tarmstrong pushed a change to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git.


    from ec2e30a  IMPALA-7140 (part 2). Create skeleton for LocalFsTable
     new 687ad44  IMPALA-7046: introduce "global" debug_actions
     new e964339  IMPALA-7150: fixes jni frame scope
     new de01eb1  IMPALA-7187: Fix test_group_impersonation running inside Docker
     new b136982  [DOCS] Added another scenario when REFRESH is required
     new 98e0126  IMPALA-5202: Disallow PREPARE:WAIT debug action
     new 48a41a7  IMPALA-7193: Fix cluster startup args in create-load-data.sh
     new 0963865  IMPALA-7175: deflake check for failed impalad
     new f3761d4  IMPALA-5763: [DOCS] Warn against setting --logbufsecs to 0
     new 0d8a368  IMPALA-5900: [DOCS] Doc fe_service_threads startup  option
     new 4a279e1  IMPALA-7140 (part 3): load partitions for FS tables
     new e62b0ec  IMPALA-7140 (part 4): support creating descriptors for FS tables
     new b970140  IMPALA-7198: [DOCS] Corrected misspelled hints
     new 23922dd  IMPALA-7191: don't call srand() at random times

The 13 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 be/src/common/init.cc                              |   2 +
 be/src/exec/exec-node.cc                           |   2 +
 be/src/exec/hdfs-table-sink.cc                     |   7 -
 be/src/exprs/hive-udf-call.cc                      |  10 +-
 be/src/runtime/coordinator.cc                      |   1 +
 be/src/runtime/data-stream-sender.cc               |   1 -
 be/src/runtime/debug-options.cc                    |  71 +++---
 be/src/runtime/krpc-data-stream-sender.cc          |   1 -
 be/src/scheduling/admission-controller.cc          |   6 +-
 be/src/service/client-request-state.cc             |   9 +-
 be/src/testutil/fault-injection-util.cc            |   2 -
 be/src/util/debug-util.cc                          | 105 ++++++++-
 be/src/util/debug-util.h                           |  49 ++--
 common/thrift/CatalogObjects.thrift                |   1 +
 common/thrift/ImpalaService.thrift                 |  21 +-
 docs/topics/impala_config_options.xml              | 249 +++------------------
 docs/topics/impala_hints.xml                       |   4 +-
 docs/topics/impala_logging.xml                     |  57 +++--
 docs/topics/impala_refresh.xml                     |  11 +-
 .../org/apache/impala/catalog/FeCatalogUtils.java  | 182 +++++++++++++++
 .../org/apache/impala/catalog/FeFsPartition.java   |  16 ++
 .../java/org/apache/impala/catalog/FeFsTable.java  |   8 +
 .../org/apache/impala/catalog/HdfsPartition.java   | 133 +++--------
 .../java/org/apache/impala/catalog/HdfsTable.java  |  54 +----
 .../apache/impala/catalog/PartitionStatsUtil.java  |  19 +-
 .../main/java/org/apache/impala/catalog/Table.java |   6 +-
 .../impala/catalog/local/DirectMetaProvider.java   |  64 ++++++
 .../impala/catalog/local/LocalFsPartition.java     | 206 +++++++++++++++++
 .../apache/impala/catalog/local/LocalFsTable.java  | 241 +++++++++++++++++++-
 .../impala/catalog/local/LocalPartitionSpec.java   |  71 ++++++
 .../apache/impala/catalog/local/LocalTable.java    |  17 +-
 .../apache/impala/catalog/local/MetaProvider.java  |  17 ++
 .../org/apache/impala/planner/HdfsScanNode.java    |  20 +-
 .../apache/impala/service/CatalogOpExecutor.java   |  21 +-
 .../java/org/apache/impala/util/MetaStoreUtil.java |  21 ++
 .../org/apache/impala/catalog/CatalogTest.java     |  13 +-
 .../impala/catalog/local/LocalCatalogTest.java     |  31 ++-
 testdata/bin/create-load-data.sh                   |   2 +-
 tests/authorization/test_authorization.py          |   5 +-
 tests/common/impala_cluster.py                     |  14 ++
 tests/custom_cluster/test_admission_controller.py  |  12 +-
 tests/failure/test_failpoints.py                   |  11 +-
 tests/query_test/test_observability.py             |   8 +-
 tests/query_test/test_udfs.py                      |   6 +-
 44 files changed, 1250 insertions(+), 557 deletions(-)
 create mode 100644 fe/src/main/java/org/apache/impala/catalog/local/LocalFsPartition.java
 create mode 100644 fe/src/main/java/org/apache/impala/catalog/local/LocalPartitionSpec.java


[impala] 11/13: IMPALA-7140 (part 4): support creating descriptors for FS tables

Posted by ta...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tarmstrong pushed a commit to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git

commit e62b0ec49ca268c074f1c1e85c884b35e4dd7627
Author: Todd Lipcon <to...@cloudera.com>
AuthorDate: Wed Jun 13 15:39:20 2018 -0700

    IMPALA-7140 (part 4): support creating descriptors for FS tables
    
    This adds the relevant methods to convert LocalFsTable and
    LocalFsPartition to thrift descriptors for consumption by the backend.
    
    Unfortunately we cannot yet enable the planner tests, since they are
    checking file counts and sizes as part of the explain output, and we
    haven't yet implemented file info fetching in the LocalCatalog.
    
    However, I was able to manually test this change by starting an impalad
    with --use_local_catalog, connecting to it from the shell, and running
    various EXPLAIN SELECT queries against tpch and functional tables. The
    explain output is more or less as expected with the exception of missing
    file info.
    
    Change-Id: I4550612eb6d1e3a324f49a9c4d24b048e45d3738
    Reviewed-on: http://gerrit.cloudera.org:8080/10735
    Reviewed-by: Vuk Ercegovac <ve...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
 common/thrift/CatalogObjects.thrift                |  1 +
 .../org/apache/impala/catalog/FeCatalogUtils.java  | 82 ++++++++++++++++++++++
 .../org/apache/impala/catalog/FeFsPartition.java   | 16 +++++
 .../java/org/apache/impala/catalog/FeFsTable.java  |  8 +++
 .../org/apache/impala/catalog/HdfsPartition.java   | 73 +++++--------------
 .../java/org/apache/impala/catalog/HdfsTable.java  | 30 ++------
 .../main/java/org/apache/impala/catalog/Table.java |  6 +-
 .../impala/catalog/local/LocalFsPartition.java     | 25 ++++++-
 .../apache/impala/catalog/local/LocalFsTable.java  | 58 ++++++++++++++-
 .../apache/impala/catalog/local/LocalTable.java    | 13 ++--
 .../org/apache/impala/planner/HdfsScanNode.java    | 20 +++---
 11 files changed, 227 insertions(+), 105 deletions(-)

diff --git a/common/thrift/CatalogObjects.thrift b/common/thrift/CatalogObjects.thrift
index 23da91f..bc068d6 100644
--- a/common/thrift/CatalogObjects.thrift
+++ b/common/thrift/CatalogObjects.thrift
@@ -239,6 +239,7 @@ struct THdfsPartitionLocation {
 }
 
 // Represents an HDFS partition
+// TODO(vercegovac): rename to TFsPartition
 struct THdfsPartition {
   1: required byte lineDelim
   2: required byte fieldDelim
diff --git a/fe/src/main/java/org/apache/impala/catalog/FeCatalogUtils.java b/fe/src/main/java/org/apache/impala/catalog/FeCatalogUtils.java
index 80ab246..bf4d230 100644
--- a/fe/src/main/java/org/apache/impala/catalog/FeCatalogUtils.java
+++ b/fe/src/main/java/org/apache/impala/catalog/FeCatalogUtils.java
@@ -30,6 +30,10 @@ import org.apache.impala.analysis.LiteralExpr;
 import org.apache.impala.analysis.NullLiteral;
 import org.apache.impala.analysis.PartitionKeyValue;
 import org.apache.impala.analysis.ToSqlUtils;
+import org.apache.impala.catalog.HdfsPartition.FileDescriptor;
+import org.apache.impala.thrift.TColumnDescriptor;
+import org.apache.impala.thrift.THdfsPartition;
+import org.apache.impala.thrift.TTableStats;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -38,6 +42,7 @@ import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
 
 /**
  * Static utility functions shared between FeCatalog implementations.
@@ -114,6 +119,15 @@ public abstract class FeCatalogUtils {
     }
   }
 
+  // TODO(todd): move to a default method in FeTable in Java8
+  public static List<TColumnDescriptor> getTColumnDescriptors(FeTable table) {
+    List<TColumnDescriptor> colDescs = Lists.<TColumnDescriptor>newArrayList();
+    for (Column col: table.getColumns()) {
+      colDescs.add(new TColumnDescriptor(col.getName(), col.getType().toThrift()));
+    }
+    return colDescs;
+  }
+
   /**
    * Returns the value of the ROW_COUNT constant, or -1 if not found.
    */
@@ -248,4 +262,72 @@ public abstract class FeCatalogUtils {
     }
     return "(" + Joiner.on(" AND " ).join(conjuncts) + ")";
   }
+
+  /**
+   * Return the most commonly-used file format within a set of partitions.
+   */
+  public static HdfsFileFormat getMajorityFormat(
+      Iterable<? extends FeFsPartition> partitions) {
+    Map<HdfsFileFormat, Integer> numPartitionsByFormat = Maps.newHashMap();
+    for (FeFsPartition partition: partitions) {
+      HdfsFileFormat format = partition.getInputFormatDescriptor().getFileFormat();
+      Integer numPartitions = numPartitionsByFormat.get(format);
+      if (numPartitions == null) {
+        numPartitions = Integer.valueOf(1);
+      } else {
+        numPartitions = Integer.valueOf(numPartitions.intValue() + 1);
+      }
+      numPartitionsByFormat.put(format, numPartitions);
+    }
+
+    int maxNumPartitions = Integer.MIN_VALUE;
+    HdfsFileFormat majorityFormat = null;
+    for (Map.Entry<HdfsFileFormat, Integer> entry: numPartitionsByFormat.entrySet()) {
+      if (entry.getValue().intValue() > maxNumPartitions) {
+        majorityFormat = entry.getKey();
+        maxNumPartitions = entry.getValue().intValue();
+      }
+    }
+    Preconditions.checkNotNull(majorityFormat);
+    return majorityFormat;
+  }
+
+  public static THdfsPartition fsPartitionToThrift(FeFsPartition part,
+      boolean includeFileDesc, boolean includeIncrementalStats) {
+    HdfsStorageDescriptor sd = part.getInputFormatDescriptor();
+    THdfsPartition thriftHdfsPart = new THdfsPartition(
+        sd.getLineDelim(),
+        sd.getFieldDelim(),
+        sd.getCollectionDelim(),
+        sd.getMapKeyDelim(),
+        sd.getEscapeChar(),
+        sd.getFileFormat().toThrift(),
+        Expr.treesToThrift(part.getPartitionValues()),
+        sd.getBlockSize());
+    thriftHdfsPart.setLocation(part.getLocationAsThrift());
+    thriftHdfsPart.setStats(new TTableStats(part.getNumRows()));
+    thriftHdfsPart.setAccess_level(part.getAccessLevel());
+    thriftHdfsPart.setIs_marked_cached(part.isMarkedCached());
+    thriftHdfsPart.setId(part.getId());
+    thriftHdfsPart.setHas_incremental_stats(part.hasIncrementalStats());
+    // IMPALA-4902: Shallow-clone the map to avoid concurrent modifications. One thread
+    // may try to serialize the returned THdfsPartition after releasing the table's lock,
+    // and another thread doing DDL may modify the map.
+    thriftHdfsPart.setHms_parameters(Maps.newHashMap(
+        includeIncrementalStats ? part.getParameters() :
+          part.getFilteredHmsParameters()));
+    if (includeFileDesc) {
+      // Add block location information
+      long numBlocks = 0;
+      long totalFileBytes = 0;
+      for (FileDescriptor fd: part.getFileDescriptors()) {
+        thriftHdfsPart.addToFile_desc(fd.toThrift());
+        numBlocks += fd.getNumFileBlocks();
+        totalFileBytes += fd.getFileLength();
+      }
+      thriftHdfsPart.setNum_blocks(numBlocks);
+      thriftHdfsPart.setTotal_file_size_bytes(totalFileBytes);
+    }
+    return thriftHdfsPart;
+  }
 }
diff --git a/fe/src/main/java/org/apache/impala/catalog/FeFsPartition.java b/fe/src/main/java/org/apache/impala/catalog/FeFsPartition.java
index 52edeb8..ab6a3eb 100644
--- a/fe/src/main/java/org/apache/impala/catalog/FeFsPartition.java
+++ b/fe/src/main/java/org/apache/impala/catalog/FeFsPartition.java
@@ -25,6 +25,7 @@ import org.apache.hadoop.fs.Path;
 import org.apache.impala.analysis.LiteralExpr;
 import org.apache.impala.catalog.HdfsPartition.FileDescriptor;
 import org.apache.impala.thrift.TAccessLevel;
+import org.apache.impala.thrift.THdfsPartitionLocation;
 import org.apache.impala.thrift.TPartitionStats;
 
 /**
@@ -68,6 +69,11 @@ public interface FeFsPartition {
   String getLocation();
 
   /**
+   * Return the location of this partition, serialized in Thrift.
+   */
+  THdfsPartitionLocation getLocationAsThrift();
+
+  /**
    * @return the location of this partition as a Path
    */
   Path getLocationPath();
@@ -146,4 +152,14 @@ public interface FeFsPartition {
    * @return the HMS parameters stored for this partition
    */
   Map<String, String> getParameters();
+
+  /**
+   * Returns the HMS partition parameters after filtering out all the partition
+   * incremental stats information.
+   *
+   * TODO(todd): consider _always_ filtering the parameters to remove incremental
+   * stats, and having a different getter which returns the already-decoded stats
+   * which are more memory-efficient anyway.
+   */
+  Map<String, String> getFilteredHmsParameters();
 }
diff --git a/fe/src/main/java/org/apache/impala/catalog/FeFsTable.java b/fe/src/main/java/org/apache/impala/catalog/FeFsTable.java
index 86bf2eb..508a0e5 100644
--- a/fe/src/main/java/org/apache/impala/catalog/FeFsTable.java
+++ b/fe/src/main/java/org/apache/impala/catalog/FeFsTable.java
@@ -100,6 +100,14 @@ public interface FeFsTable extends FeTable {
   boolean isAvroTable();
 
   /**
+   * @return the format that the majority of partitions in this table use
+   *
+   * TODO(todd): this API needs to be removed, since it depends on loading all
+   * partitions even when scanning few.
+   */
+  public HdfsFileFormat getMajorityFormat();
+
+  /**
    * @param totalBytes_ the known number of bytes in the table
    * @return Returns an estimated row count for the given number of file bytes
    */
diff --git a/fe/src/main/java/org/apache/impala/catalog/HdfsPartition.java b/fe/src/main/java/org/apache/impala/catalog/HdfsPartition.java
index 26f8c30..640aaa1 100644
--- a/fe/src/main/java/org/apache/impala/catalog/HdfsPartition.java
+++ b/fe/src/main/java/org/apache/impala/catalog/HdfsPartition.java
@@ -32,9 +32,7 @@ import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
 import org.apache.impala.analysis.Expr;
 import org.apache.impala.analysis.LiteralExpr;
-import org.apache.impala.analysis.NullLiteral;
 import org.apache.impala.analysis.PartitionKeyValue;
-import org.apache.impala.analysis.ToSqlUtils;
 import org.apache.impala.common.FileSystemUtil;
 import org.apache.impala.common.Pair;
 import org.apache.impala.common.Reference;
@@ -47,9 +45,9 @@ import org.apache.impala.thrift.TExpr;
 import org.apache.impala.thrift.TExprNode;
 import org.apache.impala.thrift.THdfsFileDesc;
 import org.apache.impala.thrift.THdfsPartition;
+import org.apache.impala.thrift.THdfsPartitionLocation;
 import org.apache.impala.thrift.TNetworkAddress;
 import org.apache.impala.thrift.TPartitionStats;
-import org.apache.impala.thrift.TTableStats;
 import org.apache.impala.util.HdfsCachingUtil;
 import org.apache.impala.util.ListMap;
 import org.slf4j.Logger;
@@ -485,9 +483,16 @@ public class HdfsPartition implements FeFsPartition, PrunablePartition {
    * Returns the storage location (HDFS path) of this partition. Should only be called
    * for partitioned tables.
    */
+  @Override
   public String getLocation() {
     return (location_ != null) ? location_.toString() : null;
   }
+
+  @Override
+  public THdfsPartitionLocation getLocationAsThrift() {
+    return location_ != null ? location_.toThrift() : null;
+  }
+
   @Override // FeFsPartition
   public Path getLocationPath() { return new Path(getLocation()); }
   @Override // FeFsPartition
@@ -733,20 +738,18 @@ public class HdfsPartition implements FeFsPartition, PrunablePartition {
       .toString();
   }
 
-  private static Predicate<String> isIncrementalStatsKey = new Predicate<String>() {
-    @Override
-    public boolean apply(String key) {
-      return !(key.startsWith(PartitionStatsUtil.INCREMENTAL_STATS_NUM_CHUNKS)
-          || key.startsWith(PartitionStatsUtil.INCREMENTAL_STATS_CHUNK_PREFIX));
-    }
-  };
+  public static Predicate<String> IS_NOT_INCREMENTAL_STATS_KEY =
+      new Predicate<String>() {
+        @Override
+        public boolean apply(String key) {
+          return !(key.startsWith(PartitionStatsUtil.INCREMENTAL_STATS_NUM_CHUNKS)
+              || key.startsWith(PartitionStatsUtil.INCREMENTAL_STATS_CHUNK_PREFIX));
+        }
+      };
 
-  /**
-   * Returns hmsParameters_ after filtering out all the partition
-   * incremental stats information.
-   */
-  private Map<String, String> getFilteredHmsParameters() {
-    return Maps.filterKeys(hmsParameters_, isIncrementalStatsKey);
+  @Override
+  public Map<String, String> getFilteredHmsParameters() {
+    return Maps.filterKeys(hmsParameters_, IS_NOT_INCREMENTAL_STATS_KEY);
   }
 
   public static HdfsPartition fromThrift(HdfsTable table,
@@ -831,44 +834,6 @@ public class HdfsPartition implements FeFsPartition, PrunablePartition {
     }
   }
 
-  public THdfsPartition toThrift(boolean includeFileDesc,
-      boolean includeIncrementalStats) {
-    List<TExpr> thriftExprs = Expr.treesToThrift(getPartitionValues());
-
-    THdfsPartition thriftHdfsPart = new THdfsPartition(
-        fileFormatDescriptor_.getLineDelim(),
-        fileFormatDescriptor_.getFieldDelim(),
-        fileFormatDescriptor_.getCollectionDelim(),
-        fileFormatDescriptor_.getMapKeyDelim(),
-        fileFormatDescriptor_.getEscapeChar(),
-        fileFormatDescriptor_.getFileFormat().toThrift(), thriftExprs,
-        fileFormatDescriptor_.getBlockSize());
-    if (location_ != null) thriftHdfsPart.setLocation(location_.toThrift());
-    thriftHdfsPart.setStats(new TTableStats(numRows_));
-    thriftHdfsPart.setAccess_level(accessLevel_);
-    thriftHdfsPart.setIs_marked_cached(isMarkedCached_);
-    thriftHdfsPart.setId(getId());
-    thriftHdfsPart.setHas_incremental_stats(hasIncrementalStats());
-    // IMPALA-4902: Shallow-clone the map to avoid concurrent modifications. One thread
-    // may try to serialize the returned THdfsPartition after releasing the table's lock,
-    // and another thread doing DDL may modify the map.
-    thriftHdfsPart.setHms_parameters(Maps.newHashMap(
-        includeIncrementalStats ? hmsParameters_ : getFilteredHmsParameters()));
-    if (includeFileDesc) {
-      // Add block location information
-      long numBlocks = 0;
-      long totalFileBytes = 0;
-      for (FileDescriptor fd: fileDescriptors_) {
-        thriftHdfsPart.addToFile_desc(fd.toThrift());
-        numBlocks += fd.getNumFileBlocks();
-        totalFileBytes += fd.getFileLength();
-      }
-      thriftHdfsPart.setNum_blocks(numBlocks);
-      thriftHdfsPart.setTotal_file_size_bytes(totalFileBytes);
-    }
-    return thriftHdfsPart;
-  }
-
   /**
    * Comparator to allow ordering of partitions by their partition-key values.
    */
diff --git a/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java b/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
index e6c34bc..13521df 100644
--- a/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
+++ b/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
@@ -1716,8 +1716,8 @@ public class HdfsTable extends Table implements FeFsTable {
     for (HdfsPartition partition: partitionMap_.values()) {
       long id = partition.getId();
       if (refPartitions == null || refPartitions.contains(id)) {
-        THdfsPartition tHdfsPartition =
-            partition.toThrift(includeFileDesc, includeIncrementalStats);
+        THdfsPartition tHdfsPartition = FeCatalogUtils.fsPartitionToThrift(
+            partition, includeFileDesc, includeIncrementalStats);
         if (tHdfsPartition.isSetHas_incremental_stats() &&
             tHdfsPartition.isHas_incremental_stats()) {
           memUsageEstimate += getColumns().size() * STATS_SIZE_PER_COLUMN_BYTES;
@@ -1736,7 +1736,8 @@ public class HdfsTable extends Table implements FeFsTable {
     }
     if (includeFileDesc) fileMetadataStats_.set(stats);
 
-    THdfsPartition prototypePartition = prototypePartition_.toThrift(false, false);
+    THdfsPartition prototypePartition = FeCatalogUtils.fsPartitionToThrift(
+        prototypePartition_, false, false);
 
     memUsageEstimate += fileMetadataStats_.numFiles * PER_FD_MEM_USAGE_BYTES +
         fileMetadataStats_.numBlocks * PER_BLOCK_MEM_USAGE_BYTES;
@@ -1777,28 +1778,7 @@ public class HdfsTable extends Table implements FeFsTable {
     // important to add the "prototype" partition as a fallback.
     Iterable<HdfsPartition> partitionsToConsider = Iterables.concat(
         partitionMap_.values(), Collections.singleton(prototypePartition_));
-    Map<HdfsFileFormat, Integer> numPartitionsByFormat = Maps.newHashMap();
-    for (HdfsPartition partition: partitionsToConsider) {
-      HdfsFileFormat format = partition.getInputFormatDescriptor().getFileFormat();
-      Integer numPartitions = numPartitionsByFormat.get(format);
-      if (numPartitions == null) {
-        numPartitions = Integer.valueOf(1);
-      } else {
-        numPartitions = Integer.valueOf(numPartitions.intValue() + 1);
-      }
-      numPartitionsByFormat.put(format, numPartitions);
-    }
-
-    int maxNumPartitions = Integer.MIN_VALUE;
-    HdfsFileFormat majorityFormat = null;
-    for (Map.Entry<HdfsFileFormat, Integer> entry: numPartitionsByFormat.entrySet()) {
-      if (entry.getValue().intValue() > maxNumPartitions) {
-        majorityFormat = entry.getKey();
-        maxNumPartitions = entry.getValue().intValue();
-      }
-    }
-    Preconditions.checkNotNull(majorityFormat);
-    return majorityFormat;
+    return FeCatalogUtils.getMajorityFormat(partitionsToConsider);
   }
 
   /**
diff --git a/fe/src/main/java/org/apache/impala/catalog/Table.java b/fe/src/main/java/org/apache/impala/catalog/Table.java
index cdeffbf..7fdc3c9 100644
--- a/fe/src/main/java/org/apache/impala/catalog/Table.java
+++ b/fe/src/main/java/org/apache/impala/catalog/Table.java
@@ -420,11 +420,7 @@ public abstract class Table extends CatalogObjectImpl implements FeTable {
    * Returns a list of thrift column descriptors ordered by position.
    */
   public List<TColumnDescriptor> getTColumnDescriptors() {
-    List<TColumnDescriptor> colDescs = Lists.<TColumnDescriptor>newArrayList();
-    for (Column col: colsByPos_) {
-      colDescs.add(new TColumnDescriptor(col.getName(), col.getType().toThrift()));
-    }
-    return colDescs;
+    return FeCatalogUtils.getTColumnDescriptors(this);
   }
 
   /**
diff --git a/fe/src/main/java/org/apache/impala/catalog/local/LocalFsPartition.java b/fe/src/main/java/org/apache/impala/catalog/local/LocalFsPartition.java
index c33b8a2..effe7c2 100644
--- a/fe/src/main/java/org/apache/impala/catalog/local/LocalFsPartition.java
+++ b/fe/src/main/java/org/apache/impala/catalog/local/LocalFsPartition.java
@@ -28,14 +28,17 @@ import org.apache.impala.catalog.FeCatalogUtils;
 import org.apache.impala.catalog.FeFsPartition;
 import org.apache.impala.catalog.FeFsTable;
 import org.apache.impala.catalog.HdfsFileFormat;
+import org.apache.impala.catalog.HdfsPartition;
 import org.apache.impala.catalog.HdfsPartition.FileDescriptor;
 import org.apache.impala.catalog.HdfsStorageDescriptor;
 import org.apache.impala.catalog.HdfsStorageDescriptor.InvalidStorageDescriptorException;
 import org.apache.impala.catalog.PartitionStatsUtil;
 import org.apache.impala.thrift.TAccessLevel;
+import org.apache.impala.thrift.THdfsPartitionLocation;
 import org.apache.impala.thrift.TPartitionStats;
 
 import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
 
 public class LocalFsPartition implements FeFsPartition {
   private final LocalFsTable table_;
@@ -72,8 +75,10 @@ public class LocalFsPartition implements FeFsPartition {
 
   @Override
   public boolean hasFileDescriptors() {
-    // TODO Auto-generated method stub
-    return false;
+    // TODO(todd): implement file fetching. Return true for now
+    // so that partition pruning can be tested -- if we return false
+    // then all partitions would be pruned.
+    return true;
   }
 
   @Override
@@ -88,6 +93,13 @@ public class LocalFsPartition implements FeFsPartition {
   }
 
   @Override
+  public THdfsPartitionLocation getLocationAsThrift() {
+    // TODO(todd): support prefix-compressed partition locations. For now,
+    // using -1 indicates that the location is a full path string.
+    return new THdfsPartitionLocation(/*prefix_index=*/-1, getLocation());
+  }
+
+  @Override
   public Path getLocationPath() {
     return new Path(getLocation());
   }
@@ -182,4 +194,13 @@ public class LocalFsPartition implements FeFsPartition {
   public Map<String, String> getParameters() {
     return msPartition_.getParameters();
   }
+
+  @Override
+  public Map<String, String> getFilteredHmsParameters() {
+    // TODO(todd): for now, copied from HdfsPartition. Eventually we would want to
+    // lazy-fetch these parameters separately for only the cases that require them,
+    // since they are quite large.
+    return Maps.filterKeys(getParameters(),
+        HdfsPartition.IS_NOT_INCREMENTAL_STATS_KEY);
+  }
 }
diff --git a/fe/src/main/java/org/apache/impala/catalog/local/LocalFsTable.java b/fe/src/main/java/org/apache/impala/catalog/local/LocalFsTable.java
index 352655c..f648ac8 100644
--- a/fe/src/main/java/org/apache/impala/catalog/local/LocalFsTable.java
+++ b/fe/src/main/java/org/apache/impala/catalog/local/LocalFsTable.java
@@ -31,20 +31,28 @@ import org.apache.impala.analysis.LiteralExpr;
 import org.apache.impala.analysis.NullLiteral;
 import org.apache.impala.catalog.CatalogException;
 import org.apache.impala.catalog.Column;
+import org.apache.impala.catalog.FeCatalogUtils;
 import org.apache.impala.catalog.FeFsPartition;
 import org.apache.impala.catalog.FeFsTable;
+import org.apache.impala.catalog.HdfsFileFormat;
 import org.apache.impala.catalog.HdfsTable;
 import org.apache.impala.catalog.HdfsPartition.FileDescriptor;
 import org.apache.impala.catalog.PrunablePartition;
+import org.apache.impala.thrift.CatalogObjectsConstants;
+import org.apache.impala.thrift.THdfsPartition;
+import org.apache.impala.thrift.THdfsTable;
 import org.apache.impala.thrift.TNetworkAddress;
 import org.apache.impala.thrift.TPartitionKeyValue;
 import org.apache.impala.thrift.TResultSet;
+import org.apache.impala.thrift.TTableDescriptor;
+import org.apache.impala.thrift.TTableType;
 import org.apache.impala.util.ListMap;
 import org.apache.thrift.TException;
 
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
 
 public class LocalFsTable extends LocalTable implements FeFsTable {
   /**
@@ -134,6 +142,12 @@ public class LocalFsTable extends LocalTable implements FeFsTable {
   }
 
   @Override
+  public HdfsFileFormat getMajorityFormat() {
+    // Needed by HdfsTableSink.
+    throw new UnsupportedOperationException("TODO: implement me");
+  }
+
+  @Override
   public long getExtrapolatedNumRows(long totalBytes) {
     // TODO Auto-generated method stub
     return 0;
@@ -151,6 +165,47 @@ public class LocalFsTable extends LocalTable implements FeFsTable {
   }
 
   @Override
+  public TTableDescriptor toThriftDescriptor(int tableId, Set<Long> referencedPartitions) {
+    Preconditions.checkNotNull(referencedPartitions);
+    Map<Long, THdfsPartition> idToPartition = Maps.newHashMap();
+    List<? extends FeFsPartition> partitions = loadPartitions(referencedPartitions);
+    for (FeFsPartition partition : partitions) {
+      idToPartition.put(partition.getId(),
+          FeCatalogUtils.fsPartitionToThrift(partition,
+              /*includeFileDesc=*/false,
+              /*includeIncrementalStats=*/false));
+    }
+
+    THdfsPartition tPrototypePartition = FeCatalogUtils.fsPartitionToThrift(
+        createPrototypePartition(),
+        /*includeFileDesc=*/false,
+        /*includeIncrementalStats=*/false);
+
+    // TODO(todd): implement avro schema support
+    // TODO(todd): set multiple_filesystems member?
+    THdfsTable hdfsTable = new THdfsTable(getHdfsBaseDir(), getColumnNames(),
+        getNullPartitionKeyValue(), schemaInfo_.getNullColumnValue(), idToPartition,
+        tPrototypePartition);
+
+    TTableDescriptor tableDesc = new TTableDescriptor(tableId, TTableType.HDFS_TABLE,
+        FeCatalogUtils.getTColumnDescriptors(this),
+        getNumClusteringCols(), name_, db_.getName());
+    tableDesc.setHdfsTable(hdfsTable);
+    return tableDesc;
+  }
+
+  private LocalFsPartition createPrototypePartition() {
+    Partition protoMsPartition = new Partition();
+    protoMsPartition.setSd(getMetaStoreTable().getSd());
+    protoMsPartition.setParameters(Collections.<String, String>emptyMap());
+    LocalPartitionSpec spec = new LocalPartitionSpec(
+        this, "", CatalogObjectsConstants.PROTOTYPE_PARTITION_ID);
+    LocalFsPartition prototypePartition = new LocalFsPartition(
+        this, spec, protoMsPartition);
+    return prototypePartition;
+  }
+
+  @Override
   public Collection<? extends PrunablePartition> getPartitions() {
     loadPartitionSpecs();
     return partitionSpecs_.values();
@@ -258,7 +313,8 @@ public class LocalFsTable extends LocalTable implements FeFsTable {
     if (partitionValueMap_ != null) return;
 
     loadPartitionSpecs();
-    ArrayList<TreeMap<LiteralExpr, HashSet<Long>>> valMapByCol = new ArrayList<>();
+    ArrayList<TreeMap<LiteralExpr, HashSet<Long>>> valMapByCol =
+        new ArrayList<>();
     ArrayList<HashSet<Long>> nullParts = new ArrayList<>();
 
     for (int i = 0; i < getNumClusteringCols(); i++) {
diff --git a/fe/src/main/java/org/apache/impala/catalog/local/LocalTable.java b/fe/src/main/java/org/apache/impala/catalog/local/LocalTable.java
index 246b691..a0a7bd7 100644
--- a/fe/src/main/java/org/apache/impala/catalog/local/LocalTable.java
+++ b/fe/src/main/java/org/apache/impala/catalog/local/LocalTable.java
@@ -19,7 +19,6 @@ package org.apache.impala.catalog.local;
 
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Set;
 
 import javax.annotation.concurrent.Immutable;
 
@@ -37,7 +36,6 @@ import org.apache.impala.catalog.StructField;
 import org.apache.impala.catalog.StructType;
 import org.apache.impala.catalog.TableLoadingException;
 import org.apache.impala.thrift.TCatalogObjectType;
-import org.apache.impala.thrift.TTableDescriptor;
 import org.apache.impala.thrift.TTableStats;
 import org.apache.thrift.TException;
 
@@ -53,7 +51,7 @@ import com.google.common.collect.Lists;
  * This class is not thread-safe. A new instance is created for
  * each catalog instance.
  */
-class LocalTable implements FeTable {
+abstract class LocalTable implements FeTable {
   protected final LocalDb db_;
   /** The lower-case name of the table. */
   protected final String name_;
@@ -181,11 +179,6 @@ class LocalTable implements FeTable {
     return schemaInfo_.tableStats_;
   }
 
-  @Override
-  public TTableDescriptor toThriftDescriptor(int tableId, Set<Long> referencedPartitions) {
-    throw new UnsupportedOperationException("TODO");
-  }
-
   /**
    * The table schema, loaded from the HMS Table object. This is common
    * to all Table implementations and includes the column definitions and
@@ -275,5 +268,9 @@ class LocalTable implements FeTable {
       Preconditions.checkArgument(colsByPos_.get(c.getPosition()) == c);
       return c.getPosition() < numClusteringCols_;
     }
+
+    protected String getNullColumnValue() {
+      return nullColumnValue_;
+    }
   }
 }
diff --git a/fe/src/main/java/org/apache/impala/planner/HdfsScanNode.java b/fe/src/main/java/org/apache/impala/planner/HdfsScanNode.java
index 378ad40..546052e 100644
--- a/fe/src/main/java/org/apache/impala/planner/HdfsScanNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/HdfsScanNode.java
@@ -49,13 +49,13 @@ import org.apache.impala.analysis.TupleDescriptor;
 import org.apache.impala.analysis.TupleId;
 import org.apache.impala.catalog.Column;
 import org.apache.impala.catalog.ColumnStats;
+import org.apache.impala.catalog.FeCatalogUtils;
 import org.apache.impala.catalog.HdfsCompression;
 import org.apache.impala.catalog.FeFsPartition;
 import org.apache.impala.catalog.FeFsTable;
 import org.apache.impala.catalog.HdfsFileFormat;
 import org.apache.impala.catalog.HdfsPartition.FileBlock;
 import org.apache.impala.catalog.HdfsPartition.FileDescriptor;
-import org.apache.impala.catalog.HdfsTable;
 import org.apache.impala.catalog.Type;
 import org.apache.impala.common.FileSystemUtil;
 import org.apache.impala.common.ImpalaException;
@@ -162,7 +162,7 @@ public class HdfsScanNode extends ScanNode {
   // Read size for Parquet and ORC footers. Matches HdfsScanner::FOOTER_SIZE in backend.
   private static final long FOOTER_SIZE = 100L * 1024L;
 
-  private final HdfsTable tbl_;
+  private final FeFsTable tbl_;
 
   // List of partitions to be scanned. Partitions have been pruned.
   private final List<? extends FeFsPartition> partitions_;
@@ -281,13 +281,13 @@ public class HdfsScanNode extends ScanNode {
       List<? extends FeFsPartition> partitions, TableRef hdfsTblRef, AggregateInfo aggInfo) {
     super(id, desc, "SCAN HDFS");
     Preconditions.checkState(desc.getTable() instanceof FeFsTable);
-    tbl_ = (HdfsTable)desc.getTable();
+    tbl_ = (FeFsTable)desc.getTable();
     conjuncts_ = conjuncts;
     partitions_ = partitions;
     sampleParams_ = hdfsTblRef.getSampleParams();
     replicaPreference_ = hdfsTblRef.getReplicaPreference();
     randomReplica_ = hdfsTblRef.getRandomReplica();
-    HdfsTable hdfsTable = (HdfsTable)hdfsTblRef.getTable();
+    FeFsTable hdfsTable = (FeFsTable)hdfsTblRef.getTable();
     Preconditions.checkState(tbl_ == hdfsTable);
     StringBuilder error = new StringBuilder();
     aggInfo_ = aggInfo;
@@ -1193,7 +1193,7 @@ public class HdfsScanNode extends ScanNode {
   protected String getNodeExplainString(String prefix, String detailPrefix,
       TExplainLevel detailLevel) {
     StringBuilder output = new StringBuilder();
-    HdfsTable table = (HdfsTable) desc_.getTable();
+    FeFsTable table = (FeFsTable) desc_.getTable();
     output.append(String.format("%s%s [%s", prefix, getDisplayLabel(),
         getDisplayLabelDetail()));
     if (detailLevel.ordinal() >= TExplainLevel.EXTENDED.ordinal() &&
@@ -1345,8 +1345,7 @@ public class HdfsScanNode extends ScanNode {
 
     Preconditions.checkState(0 < numNodes_ && numNodes_ <= scanRangeSize);
     Preconditions.checkNotNull(desc_);
-    Preconditions.checkState(desc_.getTable() instanceof HdfsTable);
-    HdfsTable table = (HdfsTable) desc_.getTable();
+    Preconditions.checkState(desc_.getTable() instanceof FeFsTable);
     List<Long> columnReservations = null;
     if (fileFormats_.contains(HdfsFileFormat.PARQUET)
         || fileFormats_.contains(HdfsFileFormat.ORC)) {
@@ -1354,8 +1353,9 @@ public class HdfsScanNode extends ScanNode {
     }
 
     int perHostScanRanges;
-    if (table.getMajorityFormat() == HdfsFileFormat.PARQUET
-        || table.getMajorityFormat() == HdfsFileFormat.ORC) {
+    HdfsFileFormat majorityFormat = FeCatalogUtils.getMajorityFormat(partitions_);
+    if (majorityFormat == HdfsFileFormat.PARQUET
+        || majorityFormat == HdfsFileFormat.ORC) {
       Preconditions.checkNotNull(columnReservations);
       // For the purpose of this estimation, the number of per-host scan ranges for
       // Parquet/ORC files are equal to the number of columns read from the file. I.e.
@@ -1475,7 +1475,7 @@ public class HdfsScanNode extends ScanNode {
    */
   private List<Long> computeMinColumnMemReservations() {
     List<Long> columnByteSizes = Lists.newArrayList();
-    HdfsTable table = (HdfsTable) desc_.getTable();
+    FeFsTable table = (FeFsTable) desc_.getTable();
     boolean havePosSlot = false;
     for (SlotDescriptor slot: desc_.getSlots()) {
       if (!slot.isMaterialized() || slot == countStarSlot_) continue;


[impala] 12/13: IMPALA-7198: [DOCS] Corrected misspelled hints

Posted by ta...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tarmstrong pushed a commit to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git

commit b9701408f26c4f21f76a6109752cd10150933cb1
Author: Alex Rodoni <ar...@cloudera.com>
AuthorDate: Fri Jun 22 10:08:41 2018 -0700

    IMPALA-7198: [DOCS] Corrected misspelled hints
    
    Change-Id: I3e3c4ed050131f811311d5fdb8634a1ea3385fb3
    Reviewed-on: http://gerrit.cloudera.org:8080/10796
    Reviewed-by: Alex Rodoni <ar...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
 docs/topics/impala_hints.xml | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/docs/topics/impala_hints.xml b/docs/topics/impala_hints.xml
index d16b7f6..6f853c1 100644
--- a/docs/topics/impala_hints.xml
+++ b/docs/topics/impala_hints.xml
@@ -157,11 +157,11 @@ CREATE -- +SHUFFLE|NOSHUFFLE
   <varname>table_clauses</varname>
   AS SELECT <varname>remainder_of_query</varname>;
 
-CREATE /* +CLUSTER|NOCLUSTER */
+CREATE /* +CLUSTERED|NOCLUSTERED */
   <varname>table_clauses</varname>
   AS SELECT <varname>remainder_of_query</varname>;
 
-CREATE -- +CLUSTER|NOCLUSTER
+CREATE -- +CLUSTERED|NOCLUSTERED
   <varname>table_clauses</varname>
   AS SELECT <varname>remainder_of_query</varname>;
 </codeblock>


[impala] 09/13: IMPALA-5900: [DOCS] Doc fe_service_threads startup option

Posted by ta...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tarmstrong pushed a commit to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git

commit 0d8a368144397d74e4ec51513f310565d4b1c1d0
Author: Alex Rodoni <ar...@cloudera.com>
AuthorDate: Thu Jun 21 18:14:18 2018 -0700

    IMPALA-5900: [DOCS] Doc fe_service_threads startup  option
    
    Change-Id: I7f0a417a4aa07b8082037fc6ff355e62ce1493e5
    Reviewed-on: http://gerrit.cloudera.org:8080/10795
    Reviewed-by: Michael Brown <mi...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
 docs/topics/impala_config_options.xml | 249 ++++------------------------------
 1 file changed, 30 insertions(+), 219 deletions(-)

diff --git a/docs/topics/impala_config_options.xml b/docs/topics/impala_config_options.xml
index 72f63ae..2f8a83c 100644
--- a/docs/topics/impala_config_options.xml
+++ b/docs/topics/impala_config_options.xml
@@ -34,32 +34,10 @@ under the License.
   <conbody>
 
     <p>
-      <indexterm audience="hidden">defaults file</indexterm>
-
-      <indexterm audience="hidden">configuration file</indexterm>
-
-      <indexterm audience="hidden">options</indexterm>
-
-      <indexterm audience="hidden">IMPALA_STATE_STORE_PORT</indexterm>
-
-      <indexterm audience="hidden">IMPALA_BACKEND_PORT</indexterm>
-
-      <indexterm audience="hidden">IMPALA_LOG_DIR</indexterm>
-
-      <indexterm audience="hidden">IMPALA_STATE_STORE_ARGS</indexterm>
-
-      <indexterm audience="hidden">IMPALA_SERVER_ARGS</indexterm>
-
-      <indexterm audience="hidden">ENABLE_CORE_DUMPS</indexterm>
-
-      <indexterm audience="hidden">core dumps</indexterm>
-
-      <indexterm audience="hidden">restarting services</indexterm>
-
-      <indexterm audience="hidden">services</indexterm>
-      The configuration options for the Impala-related daemons let you choose which hosts and
-      ports to use for the services that run on a single host, specify directories for logging,
-      control resource usage and security, and specify other aspects of the Impala software.
+      The configuration options for the Impala daemons let you choose which
+      hosts and ports to use for the services that run on a single host, specify
+      directories for logging, control resource usage and security, and specify
+      other aspects of the Impala software.
     </p>
 
     <p outputclass="toc inpage"/>
@@ -72,8 +50,10 @@ under the License.
 
     <conbody>
 
-      <p> The Impala server, statestore, and catalog services start up using values provided in a
-        defaults file, <filepath>/etc/default/impala</filepath>. </p>
+      <p>
+        The Impala server, statestore, and catalog services start up using values provided in a
+        defaults file, <filepath>/etc/default/impala</filepath>.
+      </p>
 
       <p>
         This file includes information about many resources used by Impala. Most of the defaults
@@ -260,22 +240,6 @@ Starting Impala Catalog Server:                            [  OK  ]</codeblock>
           </p>
         </li>
 
-<!-- Removing this reference now that the options are de-emphasized / desupported in Impala 2.3 and up.
-        <li rev="1.2">
-          <p>
-          Options for resource management, in conjunction with the YARN component. These options include
-          <codeph>-enable_rm</codeph> and <codeph>-cgroup_hierarchy_path</codeph>.
-          <ph rev="1.4.0">Additional options to help fine-tune the resource estimates are
-          <codeph>-—rm_always_use_defaults</codeph>,
-          <codeph>-—rm_default_memory=<varname>size</varname></codeph>, and
-          <codeph>-—rm_default_cpu_cores</codeph>.</ph> For details about these options, see
-          <xref href="impala_resource_management.xml#rm_options"/>. See
-          <xref href="impala_resource_management.xml#resource_management"/> for information about resource
-          management in general.
-          </p>
-        </li>
--->
-
         <li>
           <p>
             During troubleshooting, <keyword keyref="support_org"/> might direct you to change other values,
@@ -285,10 +249,6 @@ Starting Impala Catalog Server:                            [  OK  ]</codeblock>
         </li>
       </ul>
 
-<!-- Removing this reference now that the options are de-emphasized / desupported in Impala 2.3 and up.
-      <p conref="impala_resource_management.xml#rm_options/resource_management_impalad_options"/>
--->
-
       <note>
         <p>
           These startup options for the <cmdname>impalad</cmdname> daemon are different from the
@@ -298,177 +258,10 @@ Starting Impala Catalog Server:                            [  OK  ]</codeblock>
         </p>
       </note>
 
-      <p audience="hidden" outputclass="toc inpage"/>
+      <p outputclass="toc inpage"/>
 
     </conbody>
 
-    <concept audience="hidden" id="config_options_impalad_details">
-
-      <title>Configuration Options for impalad Daemon</title>
-
-      <conbody>
-
-        <p>
-          Some common settings to change include:
-        </p>
-
-        <ul>
-          <li>
-            <p>
-              Statestore address. Where practical, put the statestore on a separate host not
-              running the <cmdname>impalad</cmdname> daemon. In that recommended configuration,
-              the <cmdname>impalad</cmdname> daemon cannot refer to the statestore server using
-              the loopback address. If the statestore is hosted on a machine with an IP address
-              of 192.168.0.27, change:
-            </p>
-<codeblock>IMPALA_STATE_STORE_HOST=127.0.0.1</codeblock>
-            <p>
-              to:
-            </p>
-<codeblock>IMPALA_STATE_STORE_HOST=192.168.0.27</codeblock>
-          </li>
-
-          <li rev="1.2">
-            <p>
-              Catalog server address. Update the <codeph>IMPALA_CATALOG_SERVICE_HOST</codeph>
-              variable, including both the hostname and the port number in the value. Where
-              practical, run the catalog server on the same host as the statestore. In that
-              recommended configuration, the <cmdname>impalad</cmdname> daemon cannot refer to
-              the catalog server using the loopback address. If the catalog service is hosted on
-              a machine with an IP address of 192.168.0.27, add the following line:
-            </p>
-<codeblock>IMPALA_CATALOG_SERVICE_HOST=192.168.0.27:26000</codeblock>
-            <p>
-              The <filepath>/etc/default/impala</filepath> defaults file currently does not
-              define an <codeph>IMPALA_CATALOG_ARGS</codeph> environment variable, but if you
-              add one it will be recognized by the service startup/shutdown script. Add a
-              definition for this variable to <filepath>/etc/default/impala</filepath> and add
-              the option <codeph>-catalog_service_host=<varname>hostname</varname></codeph>. If
-              the port is different than the default 26000, also add the option
-              <codeph>-catalog_service_port=<varname>port</varname></codeph>.
-            </p>
-          </li>
-
-          <li id="mem_limit">
-            Memory limits. You can limit the amount of memory available to Impala. For example,
-            to allow Impala to use no more than 70% of system memory, change:
-<!-- Note: also needs to be updated for each release to reflect latest /etc/default/impala. -->
-<codeblock>export IMPALA_SERVER_ARGS=${IMPALA_SERVER_ARGS:- \
-    -log_dir=${IMPALA_LOG_DIR} \
-    -state_store_port=${IMPALA_STATE_STORE_PORT} \
-    -state_store_host=${IMPALA_STATE_STORE_HOST} \
-    -be_port=${IMPALA_BACKEND_PORT}}</codeblock>
-            <p>
-              to:
-            </p>
-<codeblock>export IMPALA_SERVER_ARGS=${IMPALA_SERVER_ARGS:- \
-    -log_dir=${IMPALA_LOG_DIR} -state_store_port=${IMPALA_STATE_STORE_PORT} \
-    -state_store_host=${IMPALA_STATE_STORE_HOST} \
-    -be_port=${IMPALA_BACKEND_PORT} -mem_limit=70%}</codeblock>
-            <p>
-              You can specify the memory limit using absolute notation such as
-              <codeph>500m</codeph> or <codeph>2G</codeph>, or as a percentage of physical
-              memory such as <codeph>60%</codeph>.
-            </p>
-
-            <note>
-              Queries that exceed the specified memory limit are aborted. Percentage limits are
-              based on the physical memory of the machine and do not consider cgroups.
-            </note>
-          </li>
-
-          <li>
-            Core dump enablement. To enable core dumps, change:
-<codeblock>export ENABLE_CORE_DUMPS=${ENABLE_COREDUMPS:-false}</codeblock>
-            <p>
-              to:
-            </p>
-<codeblock>export ENABLE_CORE_DUMPS=${ENABLE_COREDUMPS:-true}</codeblock>
-            <note>
-              The location of core dump files may vary according to your operating system
-              configuration. Other security settings may prevent Impala from writing core dumps
-              even when this option is enabled.
-            </note>
-          </li>
-
-          <li>
-            Authorization using the open source Sentry plugin. Specify the
-            <codeph>-server_name</codeph> and <codeph>-authorization_policy_file</codeph>
-            options as part of the <codeph>IMPALA_SERVER_ARGS</codeph> and
-            <codeph>IMPALA_STATE_STORE_ARGS</codeph> settings to enable the core Impala support
-            for authentication. See <xref href="impala_authorization.xml#secure_startup"/> for
-            details.
-          </li>
-
-          <li>
-            Auditing for successful or blocked Impala queries, another aspect of security.
-            Specify the <codeph>-audit_event_log_dir=<varname>directory_path</varname></codeph>
-            option and optionally the
-            <codeph>-max_audit_event_log_file_size=<varname>number_of_queries</varname></codeph>
-            and <codeph>-abort_on_failed_audit_event</codeph> options as part of the
-            <codeph>IMPALA_SERVER_ARGS</codeph> settings, for each Impala node, to enable and
-            customize auditing. See <xref href="impala_auditing.xml#auditing"/> for details.
-          </li>
-
-          <li>
-            Password protection for the Impala web UI, which listens on port 25000 by default.
-            This feature involves adding some or all of the
-            <codeph>--webserver_password_file</codeph>,
-            <codeph>--webserver_authentication_domain</codeph>, and
-            <codeph>--webserver_certificate_file</codeph> options to the
-            <codeph>IMPALA_SERVER_ARGS</codeph> and <codeph>IMPALA_STATE_STORE_ARGS</codeph>
-            settings. See <xref href="impala_security_webui.xml"/> for details.
-          </li>
-
-          <li id="default_query_options">
-            Another setting you might add to <codeph>IMPALA_SERVER_ARGS</codeph> is:
-<codeblock>-default_query_options='<varname>option</varname>=<varname>value</varname>,<varname>option</varname>=<varname>value</varname>,...'
-</codeblock>
-            These options control the behavior of queries performed by this
-            <cmdname>impalad</cmdname> instance. The option values you specify here override the
-            default values for <xref href="impala_query_options.xml#query_options">Impala query
-            options</xref>, as shown by the <codeph>SET</codeph> statement in
-            <cmdname>impala-shell</cmdname>.
-          </li>
-
-<!-- Removing this reference now that the options are de-emphasized / desupported in Impala 2.3 and up.
-          <li rev="1.2">
-            Options for resource management, in conjunction with the YARN component. These options
-            include <codeph>-enable_rm</codeph> and <codeph>-cgroup_hierarchy_path</codeph>.
-            <ph rev="1.4.0">Additional options to help fine-tune the resource estimates are
-            <codeph>-—rm_always_use_defaults</codeph>,
-            <codeph>-—rm_default_memory=<varname>size</varname></codeph>, and
-            <codeph>-—rm_default_cpu_cores</codeph>.</ph> For details about these options, see
-            <xref href="impala_resource_management.xml#rm_options"/>. See
-            <xref href="impala_resource_management.xml#resource_management"/> for information about resource
-            management in general.
-          </li>
--->
-
-          <li>
-            During troubleshooting, <keyword keyref="support_org"/> might direct you to change other values,
-            particularly for <codeph>IMPALA_SERVER_ARGS</codeph>, to work around issues or
-            gather debugging information.
-          </li>
-        </ul>
-
-<!-- Removing this reference now that the options are de-emphasized / desupported in Impala 2.3 and up.
-        <p conref="impala_resource_management.xml#rm_options/resource_management_impalad_options"/>
--->
-
-        <note>
-          <p>
-            These startup options for the <cmdname>impalad</cmdname> daemon are different from
-            the command-line options for the <cmdname>impala-shell</cmdname> command. For the
-            <cmdname>impala-shell</cmdname> options, see
-            <xref href="impala_shell_options.xml#shell_options"/>.
-          </p>
-        </note>
-
-      </conbody>
-
-    </concept>
-
     <concept audience="hidden" id="config_options_statestored_details">
 
       <title>Configuration Options for statestored Daemon</title>
@@ -523,9 +316,27 @@ Starting Impala Catalog Server:                            [  OK  ]</codeblock>
     <conbody>
 
       <p>
-        The <codeph>impalad</codeph> daemon implements the main Impala service, which performs
-        query processing and reads and writes the data files.
-      </p>
+        The <codeph>impalad</codeph> daemon implements the main Impala
+        service, which performs query processing and reads from and writes to the data
+        files. Some of the noteworthy options are:
+        <ul>
+          <li>
+            The <codeph>fe_service_threads</codeph> option specifies the
+            maximum number of concurrent client connections allowed. The
+            default value is 64 with which 64 queries can run
+              simultaneously.
+            <p>
+              If you have more clients trying to connect to
+              Impala than the value of this setting, the later arriving clients
+              have to wait until previous clients disconnect. You can increase
+              this value to allow more client connections. However, a large value
+              means more threads to be maintained even if most of the connections
+              are idle, and it could negatively impact query latency. Client
+              applications should use the connection pool to avoid need for
+              large number of sessions.
+            </p>
+          </li>
+        </ul></p>
 
     </conbody>
 


[impala] 07/13: IMPALA-7175: deflake check for failed impalad

Posted by ta...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tarmstrong pushed a commit to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git

commit 0963865da5de6e085c5af128e4af46372c6f09dd
Author: Vuk Ercegovac <ve...@cloudera.com>
AuthorDate: Sat Jun 16 23:20:37 2018 -0700

    IMPALA-7175: deflake check for failed impalad
    
    test_native_functions_race checks for an impalad crash
    by testing whether the number of impalads at the start and
    end of the test is the same. A recent run was flaky since
    the number of impalads at the start was incorrectly found
    to be 2. This fix tries to make the test most robust by
    determining the number of impalads based on how many
    can evaluate a trivial test query. For these tests, its
    assumed that the number of coordinators is the same as
    the number of impalads in the cluster.
    
    Change-Id: I97c6b398e43c6abb1df2b1783c26159137f14fa4
    Reviewed-on: http://gerrit.cloudera.org:8080/10745
    Reviewed-by: Impala Public Jenkins <im...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
 tests/common/impala_cluster.py | 14 ++++++++++++++
 tests/query_test/test_udfs.py  |  6 +++---
 2 files changed, 17 insertions(+), 3 deletions(-)

diff --git a/tests/common/impala_cluster.py b/tests/common/impala_cluster.py
index 9ff7318..d42c450 100644
--- a/tests/common/impala_cluster.py
+++ b/tests/common/impala_cluster.py
@@ -94,6 +94,20 @@ class ImpalaCluster(object):
     LOG.info("Cluster: " + str(self.impalads))
     return choice([impalad for impalad in self.impalads if impalad != other_impalad])
 
+  def num_responsive_coordinators(self):
+    """Find the number of impalad coordinators that can evaluate a test query."""
+    n = 0
+    for impalad in self.impalads:
+      try:
+        client = impalad.service.create_beeswax_client()
+        result = client.execute("select 1")
+        assert result.success
+        ++n
+      except Exception as e: print e
+      finally:
+        client.close()
+    return n
+
   def __build_impala_process_lists(self):
     """
     Gets all the running Impala procs (with start arguments) on the machine.
diff --git a/tests/query_test/test_udfs.py b/tests/query_test/test_udfs.py
index 9a365b5..e93f511 100644
--- a/tests/query_test/test_udfs.py
+++ b/tests/query_test/test_udfs.py
@@ -321,8 +321,9 @@ class TestUdfExecution(TestUdfBase):
     udf_path = get_fs_path('/test-warehouse/libTestUdfs.so')
 
     # Tracks number of impalads prior to tests to check that none have crashed.
+    # All impalads are assumed to be coordinators.
     cluster = ImpalaCluster()
-    exp_num_impalads = len(cluster.impalads)
+    exp_num_coordinators = cluster.num_responsive_coordinators()
 
     setup_client = self.create_impala_client()
     setup_query = create_fn_to_use.format(unique_database, udf_path)
@@ -375,8 +376,7 @@ class TestUdfExecution(TestUdfBase):
     for e in errors: print e
 
     # Checks that no impalad has crashed.
-    cluster.refresh()
-    assert len(cluster.impalads) == exp_num_impalads
+    assert cluster.num_responsive_coordinators() == exp_num_coordinators
 
   def test_ir_functions(self, vector, unique_database):
     if vector.get_value('exec_option')['disable_codegen']:


[impala] 03/13: IMPALA-7187: Fix test_group_impersonation running inside Docker

Posted by ta...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tarmstrong pushed a commit to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git

commit de01eb10cc68c761797d4e3fe2c1e0f3b950ab83
Author: Fredy Wijaya <fw...@cloudera.com>
AuthorDate: Wed Jun 20 00:00:13 2018 +0000

    IMPALA-7187: Fix test_group_impersonation running inside Docker
    
    test_group_impersonation fails when running with test-with-docker.py
    because os.getgroups() returns empty in Docker for the authorized
    proxy groups which results in denying all access. The patch is to use
    a group name from a current GID.
    
    Testing:
    - Ran all test_authorization with test-with-docker.py.
    
    Change-Id: Icb6089273fd9bc3763cb45f0591610b04a6b232e
    Reviewed-on: http://gerrit.cloudera.org:8080/10772
    Reviewed-by: Impala Public Jenkins <im...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
 tests/authorization/test_authorization.py | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/tests/authorization/test_authorization.py b/tests/authorization/test_authorization.py
index 5b4bccd..3e6c56e 100644
--- a/tests/authorization/test_authorization.py
+++ b/tests/authorization/test_authorization.py
@@ -36,9 +36,6 @@ from tests.util.filesystem_utils import WAREHOUSE
 
 AUTH_POLICY_FILE = "%s/authz-policy.ini" % WAREHOUSE
 
-def get_groups():
-  return [grp.getgrgid(group).gr_name for group in os.getgroups()]
-
 class TestAuthorization(CustomClusterTestSuite):
   AUDIT_LOG_DIR = tempfile.mkdtemp(dir=os.getenv('LOG_DIR'))
 
@@ -192,7 +189,7 @@ class TestAuthorization(CustomClusterTestSuite):
         --authorized_proxy_group_config=foo=bar;hue=%s\
         --abort_on_failed_audit_event=false\
         --audit_event_log_dir=%s" % (AUTH_POLICY_FILE,
-                                     ','.join(get_groups()),
+                                     grp.getgrgid(os.getgid()).gr_name,
                                      AUDIT_LOG_DIR))
   def test_group_impersonation(self):
     """End-to-end group impersonation + authorization test"""


[impala] 04/13: [DOCS] Added another scenario when REFRESH is required

Posted by ta...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tarmstrong pushed a commit to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git

commit b13698257657dc0c00bbe4b5251d188c807987d9
Author: Alex Rodoni <ar...@cloudera.com>
AuthorDate: Wed Jun 20 10:54:32 2018 -0700

    [DOCS] Added another scenario when REFRESH is required
    
    Change-Id: Ifff8f6b6f834402a158312d57076a84ad1eeab45
    Reviewed-on: http://gerrit.cloudera.org:8080/10773
    Reviewed-by: Vuk Ercegovac <ve...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
 docs/topics/impala_refresh.xml | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)

diff --git a/docs/topics/impala_refresh.xml b/docs/topics/impala_refresh.xml
index cdda8f0..2ed6971 100644
--- a/docs/topics/impala_refresh.xml
+++ b/docs/topics/impala_refresh.xml
@@ -86,13 +86,10 @@ under the License.
     </p>
 
     <ul>
-      <li>
-        Deleting or adding files.
-        <p>
-          For example, after loading new data files into the HDFS data directory for the table,
-          including inserting data from Hive via <codeph>INSERT</codeph> or <codeph>LOAD
-          DATA</codeph>.
-        </p>
+      <li> Deleting, adding, or modifying files. <p> For example, after loading
+          new data files into the HDFS data directory for the table, appending
+          to an existing HDFS file, inserting data from Hive via
+            <codeph>INSERT</codeph> or <codeph>LOAD DATA</codeph>. </p>
       </li>
 
       <li>


[impala] 06/13: IMPALA-7193: Fix cluster startup args in create-load-data.sh

Posted by ta...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tarmstrong pushed a commit to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git

commit 48a41a79621fbc0184e634f812b118a45d315682
Author: Joe McDonnell <jo...@cloudera.com>
AuthorDate: Thu Jun 21 10:56:02 2018 -0700

    IMPALA-7193: Fix cluster startup args in create-load-data.sh
    
    The minicluster args for dataload changed to
    a bash array in IMPALA-7119, and this requires
    a special syntax to derefence and get the whole
    array.
    
    This fixes the invocation to use the right
    syntax ($BASH_VAR[@] rather than $BASH_VAR).
    
    Change-Id: Ie9a24c0e9fa34e43697b16b48cf219f47f30c0cc
    Reviewed-on: http://gerrit.cloudera.org:8080/10782
    Reviewed-by: Philip Zeyliger <ph...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
 testdata/bin/create-load-data.sh | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/testdata/bin/create-load-data.sh b/testdata/bin/create-load-data.sh
index 0c1ea7d..077a7e2 100755
--- a/testdata/bin/create-load-data.sh
+++ b/testdata/bin/create-load-data.sh
@@ -144,7 +144,7 @@ function start-impala {
   fi
   START_CLUSTER_ARGS_INT+=("${START_CLUSTER_ARGS}")
   ${IMPALA_HOME}/bin/start-impala-cluster.py --log_dir=${IMPALA_DATA_LOADING_LOGS_DIR} \
-    ${START_CLUSTER_ARGS_INT}
+    ${START_CLUSTER_ARGS_INT[@]}
 }
 
 function restart-cluster {


[impala] 01/13: IMPALA-7046: introduce "global" debug_actions

Posted by ta...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tarmstrong pushed a commit to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git

commit 687ad447cd2cfa4cb3c5c8a54e662cd167d888f3
Author: Dan Hecht <dh...@cloudera.com>
AuthorDate: Mon Jun 11 16:30:06 2018 -0700

    IMPALA-7046: introduce "global" debug_actions
    
    The motivation is to add jitter to backend startup in test_failpoints.
    The race in IMPALA-7033 can be reproduced by adding jitter to the exec
    rpcs when some backends fail. Let's add jitter to test_failpoints to get
    better coverage of exec startup races.
    
    This builds on top of the debug action extensions added in the async
    admission control patch by allowing the new "global" debug actions
    (i.e. actions that can be used in points outside of the ExecNodes).
    See the code comments for details.
    
    For now, we're only using the SLEEP and JITTER commands, but I've
    included a FAIL command as well since I'll want to use that to write a
    test for IMPALA-6788 to simulate exec rpc failure.
    
    Note that I don't bother resolving the actions ahead of time (like we do
    for ExecNode actions). It doesn't seem worth it since the resolution
    only needs to occur after we've matched the label and I don't expect the
    same label to be hit many times within a single thread. We can always
    optimize this later if needed.
    
    Testing:
    - Verified that test_failpoints can reproduce the race in
      IMPALA-7033 by reverting that fix and testing.
    - Ran the modified tests and grepped the impalad log to see
      that the sleeps are still occuring.
    - Manually verify global FAIL command (in a build with another patch).
    - Manually verified invalid debug_actions (both ExecNode and global)
    
    Change-Id: I77663a539be18711a4f12c470ffd7474e3d69388
    Reviewed-on: http://gerrit.cloudera.org:8080/10690
    Reviewed-by: Impala Public Jenkins <im...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
    Reviewed-on: http://gerrit.cloudera.org:8080/12548
    Reviewed-by: Tim Armstrong <ta...@cloudera.com>
---
 be/src/runtime/coordinator.cc                     |   1 +
 be/src/runtime/debug-options.cc                   |  66 ++++++++------
 be/src/scheduling/admission-controller.cc         |   6 +-
 be/src/service/client-request-state.cc            |   9 +-
 be/src/util/debug-util.cc                         | 105 ++++++++++++++++++++--
 be/src/util/debug-util.h                          |  49 ++++++----
 common/thrift/ImpalaService.thrift                |  21 +++--
 tests/custom_cluster/test_admission_controller.py |  12 +--
 tests/failure/test_failpoints.py                  |   3 +
 tests/query_test/test_observability.py            |   8 +-
 10 files changed, 205 insertions(+), 75 deletions(-)

diff --git a/be/src/runtime/coordinator.cc b/be/src/runtime/coordinator.cc
index 5ddb010..22930a4 100644
--- a/be/src/runtime/coordinator.cc
+++ b/be/src/runtime/coordinator.cc
@@ -334,6 +334,7 @@ void Coordinator::StartBackendExec() {
   for (BackendState* backend_state: backend_states_) {
     ExecEnv::GetInstance()->exec_rpc_thread_pool()->Offer(
         [backend_state, this, &debug_options]() {
+          DebugActionNoFail(schedule_.query_options(), "COORD_BEFORE_EXEC_RPC");
           backend_state->Exec(query_ctx(), debug_options, filter_routing_table_,
               exec_rpcs_complete_barrier_.get());
         });
diff --git a/be/src/runtime/debug-options.cc b/be/src/runtime/debug-options.cc
index 193daee..6e5062d 100644
--- a/be/src/runtime/debug-options.cc
+++ b/be/src/runtime/debug-options.cc
@@ -16,10 +16,14 @@
 // under the License.
 
 #include <boost/algorithm/string.hpp>
+#include <gutil/strings/substitute.h>
 
 #include "runtime/debug-options.h"
+#include "util/debug-util.h"
 #include "common/logging.h"
 
+#include "common/names.h"
+
 using namespace impala;
 using namespace std;
 using namespace boost;
@@ -33,33 +37,42 @@ DebugOptions::DebugOptions(const TQueryOptions& query_options)
     // signal not set
     return;
   }
+  const DebugActionTokens& actions = TokenizeDebugActions(query_options.debug_action);
+  for (const vector<string>& components : actions) {
+    // This will filter out global debug actions which only have two components.
+    if (components.size() < 3 || components.size() > 4) continue;
 
-  vector<string> components;
-  split(components, query_options.debug_action, is_any_of(":"), token_compress_on);
-  if (components.size() < 3 || components.size() > 4) return;
-
-  const string* phase_str;
-  const string* action_str;
-  if (components.size() == 3) {
-    instance_idx_ = -1;
-    node_id_ = atoi(components[0].c_str());
-    phase_str = &components[1];
-    action_str = &components[2];
-  } else {
-    instance_idx_ = atoi(components[0].c_str());
-    node_id_ = atoi(components[1].c_str());
-    phase_str = &components[2];
-    action_str = &components[3];
-  }
-  phase_ = GetExecNodePhase(*phase_str);
-  if (!GetDebugAction(*action_str, &action_, &action_param_)) {
-    LOG(WARNING) << "Invalid debug action " << *action_str;
-    phase_ = TExecNodePhase::INVALID;
-    return;
+    const string* phase_str;
+    const string* action_str;
+    if (components.size() == 3) {
+      instance_idx_ = -1;
+      node_id_ = atoi(components[0].c_str());
+      phase_str = &components[1];
+      action_str = &components[2];
+    } else {
+      instance_idx_ = atoi(components[0].c_str());
+      node_id_ = atoi(components[1].c_str());
+      phase_str = &components[2];
+      action_str = &components[3];
+    }
+    phase_ = GetExecNodePhase(*phase_str);
+    if (phase_ == TExecNodePhase::INVALID) {
+      LOG(WARNING) << Substitute("Invalid debug_action phase $0", *phase_str);
+      return;
+    }
+    if (!GetDebugAction(*action_str, &action_, &action_param_)) {
+      LOG(WARNING) << Substitute("Invalid debug_action command $0", *action_str);
+      phase_ = TExecNodePhase::INVALID;
+      return;
+    }
+    if (phase_ == TExecNodePhase::CLOSE && action_ == TDebugAction::WAIT) {
+      LOG(WARNING) << "Do not use CLOSE:WAIT debug actions because nodes cannot be "
+          "cancelled in Close()";
+      phase_ = TExecNodePhase::INVALID;
+      return;
+    }
+    return; // Found ExecNode debug action
   }
-  DCHECK(!(phase_ == TExecNodePhase::CLOSE && action_ == TDebugAction::WAIT))
-      << "Do not use CLOSE:WAIT debug actions because nodes cannot be cancelled in "
-         "Close()";
 }
 
 TExecNodePhase::type DebugOptions::GetExecNodePhase(const string& key) {
@@ -76,8 +89,7 @@ TExecNodePhase::type DebugOptions::GetExecNodePhase(const string& key) {
 bool DebugOptions::GetDebugAction(
     const string& action, TDebugAction::type* type, string* action_param) {
   // Either "ACTION_TYPE" or "ACTION_TYPE@<integer value>".
-  vector<string> tokens;
-  split(tokens, action, is_any_of("@"), token_compress_on);
+  vector<string> tokens = TokenizeDebugActionParams(action);
   if (tokens.size() < 1 || tokens.size() > 2) return false;
   if (tokens.size() == 2) *action_param = tokens[1];
   for (auto& entry : _TDebugAction_VALUES_TO_NAMES) {
diff --git a/be/src/scheduling/admission-controller.cc b/be/src/scheduling/admission-controller.cc
index 48b3910..ac176f4 100644
--- a/be/src/scheduling/admission-controller.cc
+++ b/be/src/scheduling/admission-controller.cc
@@ -41,9 +41,6 @@ DEFINE_int64(queue_wait_timeout_ms, 60 * 1000, "Maximum amount of time (in "
 
 namespace impala {
 
-// Available 'sleep_label' string that can be used in the debug_action query option.
-static const string SLEEP_AFTER_ADMISSION_OUTCOME_MS = "SLEEP_AFTER_ADMISSION_OUTCOME_MS";
-
 /// Convenience method.
 std::string PrintBytes(int64_t value) {
   return PrettyPrinter::Print(value, TUnit::BYTES);
@@ -628,7 +625,8 @@ Status AdmissionController::AdmitQuery(QuerySchedule* schedule,
       Substitute(
           PROFILE_INFO_VAL_INITIAL_QUEUE_REASON, wait_time_ms, not_admitted_reason));
 
-  SleepIfSetInDebugOptions(schedule->query_options(), SLEEP_AFTER_ADMISSION_OUTCOME_MS);
+  // Disallow the FAIL action here. It would leave the queue in an inconsistent state.
+  DebugActionNoFail(schedule->query_options(), "AC_AFTER_ADMISSION_OUTCOME");
 
   {
     lock_guard<mutex> lock(admission_ctrl_lock_);
diff --git a/be/src/service/client-request-state.cc b/be/src/service/client-request-state.cc
index 09ad4e4..fefe5cb 100644
--- a/be/src/service/client-request-state.cc
+++ b/be/src/service/client-request-state.cc
@@ -64,11 +64,6 @@ static const string TABLES_MISSING_STATS_KEY = "Tables Missing Stats";
 static const string TABLES_WITH_CORRUPT_STATS_KEY = "Tables With Corrupt Table Stats";
 static const string TABLES_WITH_MISSING_DISK_IDS_KEY = "Tables With Missing Disk Ids";
 
-// Available 'sleep_label' strings that can be used in the debug_action query option.
-static const string SLEEP_BEFORE_ADMISSION_MS = "SLEEP_BEFORE_ADMISSION_MS";
-static const string SLEEP_AFTER_COORDINATOR_STARTS_MS =
-    "SLEEP_AFTER_COORDINATOR_STARTS_MS";
-
 ClientRequestState::ClientRequestState(
     const TQueryCtx& query_ctx, ExecEnv* exec_env, Frontend* frontend,
     ImpalaServer* server, shared_ptr<ImpalaServer::SessionState> session)
@@ -488,7 +483,7 @@ Status ClientRequestState::ExecAsyncQueryOrDmlRequest(
 }
 
 void ClientRequestState::FinishExecQueryOrDmlRequest() {
-  SleepIfSetInDebugOptions(schedule_->query_options(), SLEEP_BEFORE_ADMISSION_MS);
+  DebugActionNoFail(schedule_->query_options(), "CRS_BEFORE_ADMISSION");
   if (exec_env_->admission_controller() != nullptr) {
     Status admit_status = ExecEnv::GetInstance()->admission_controller()->AdmitQuery(
         schedule_.get(), &admit_outcome_);
@@ -500,7 +495,7 @@ void ClientRequestState::FinishExecQueryOrDmlRequest() {
   coord_.reset(new Coordinator(*schedule_, query_events_));
   Status exec_status = coord_->Exec();
 
-  SleepIfSetInDebugOptions(schedule_->query_options(), SLEEP_AFTER_COORDINATOR_STARTS_MS);
+  DebugActionNoFail(schedule_->query_options(), "CRS_AFTER_COORD_STARTS");
 
   bool cancelled = false;
   Status cancellation_status;
diff --git a/be/src/util/debug-util.cc b/be/src/util/debug-util.cc
index 7a31748..f305943 100644
--- a/be/src/util/debug-util.cc
+++ b/be/src/util/debug-util.cc
@@ -18,6 +18,7 @@
 #include "util/debug-util.h"
 
 #include <iomanip>
+#include <random>
 #include <sstream>
 #include <boost/tokenizer.hpp>
 
@@ -42,6 +43,9 @@ extern void DumpStackTraceToString(std::string* s);
 #include "common/names.h"
 
 using boost::char_separator;
+using boost::is_any_of;
+using boost::split;
+using boost::token_compress_on;
 using boost::tokenizer;
 using namespace beeswax;
 using namespace parquet;
@@ -286,13 +290,102 @@ string GetBackendString() {
   return Substitute("$0:$1", FLAGS_hostname, FLAGS_be_port);
 }
 
-void SleepIfSetInDebugOptionsImpl(
-    const TQueryOptions& query_options, const string& sleep_label) {
-  vector<string> components;
-  boost::split(components, query_options.debug_action, boost::is_any_of(":"));
-  if (components.size() == 2 && components[0].compare(sleep_label) == 0) {
-    SleepForMs(atoi(components[1].c_str()));
+DebugActionTokens TokenizeDebugActions(const string& debug_actions) {
+  DebugActionTokens results;
+  list<string> actions;
+  split(actions, debug_actions, is_any_of("|"), token_compress_on);
+  for (const string& a : actions) {
+    vector<string> components;
+    split(components, a, is_any_of(":"), token_compress_on);
+    results.push_back(components);
   }
+  return results;
+}
+
+vector<string> TokenizeDebugActionParams(const string& action) {
+  vector<string> tokens;
+  split(tokens, action, is_any_of("@"), token_compress_on);
+  return tokens;
+}
+
+/// Helper to DebugActionImpl(). Given a probability as a string (e.g. "0.3"),
+/// determine whether the action should be executed, as returned in 'should_execute'.
+/// Returns true if the parsing was successful.
+static bool ParseProbability(const string& prob_str, bool* should_execute) {
+  StringParser::ParseResult parse_result;
+  double probability = StringParser::StringToFloat<double>(
+      prob_str.c_str(), prob_str.size(), &parse_result);
+  if (parse_result != StringParser::PARSE_SUCCESS ||
+      probability < 0.0 || probability > 1.0) {
+    return false;
+  }
+  // +1L ensures probability of 0.0 and 1.0 work as expected.
+  *should_execute = rand() < probability * (RAND_MAX + 1L);
+  return true;
+}
+
+Status DebugActionImpl(
+    const TQueryOptions& query_options, const char* label) {
+  const DebugActionTokens& action_list = TokenizeDebugActions(
+      query_options.debug_action);
+  static const char ERROR_MSG[] = "Invalid debug_action $0:$1 ($2)";
+  for (const vector<string>& components : action_list) {
+    if (components.size() != 2 || components[0].compare(label) != 0) continue;
+    // 'tokens' becomes {command, param0, param1, ... }
+    vector<string> tokens = TokenizeDebugActionParams(components[1]);
+    DCHECK_GE(tokens.size(), 1);
+    const string& cmd = tokens[0];
+    int sleep_millis = 0;
+    if (cmd.compare("SLEEP") == 0) {
+      // SLEEP@<millis>
+      if (tokens.size() != 2) {
+        return Status(Substitute(ERROR_MSG, components[0], components[1],
+                "expected SLEEP@<ms>"));
+      }
+      sleep_millis = atoi(tokens[1].c_str());
+    } else if (cmd.compare("JITTER") == 0) {
+      // JITTER@<millis>[@<probability>}
+      if (tokens.size() < 2 || tokens.size() > 3) {
+        return Status(Substitute(ERROR_MSG, components[0], components[1],
+                "expected JITTER@<ms>[@<probability>]"));
+      }
+      int max_millis = atoi(tokens[1].c_str());
+      if (tokens.size() == 3) {
+        bool should_execute = true;
+        if (!ParseProbability(tokens[2], &should_execute)) {
+          return Status(Substitute(ERROR_MSG, components[0], components[1],
+                  "invalid probability"));
+        }
+        if (!should_execute) continue;
+      }
+      sleep_millis = rand() % (max_millis + 1);
+    } else if (cmd.compare("FAIL") == 0) {
+      // FAIL[@<probability>]
+      if (tokens.size() > 2) {
+        return Status(Substitute(ERROR_MSG, components[0], components[1],
+                "expected FAIL[@<probability>]"));
+      }
+      if (tokens.size() == 2) {
+        bool should_execute = true;
+        if (!ParseProbability(tokens[1], &should_execute)) {
+          return Status(Substitute(ERROR_MSG, components[0], components[1],
+                  "invalid probability"));
+        }
+        if (!should_execute) continue;
+      }
+      return Status(TErrorCode::INTERNAL_ERROR, Substitute("Debug Action: $0:$1",
+              components[0], components[1]));
+    } else {
+      return Status(Substitute(ERROR_MSG, components[0], components[1],
+              "invalid command"));
+    }
+    if (sleep_millis > 0) {
+      VLOG(1) << Substitute("Debug Action: $0:$1 sleeping for $2 ms",
+          components[0], components[1], sleep_millis);
+      SleepForMs(sleep_millis);
+    }
+  }
+  return Status::OK();
 }
 
 }
diff --git a/be/src/util/debug-util.h b/be/src/util/debug-util.h
index 0978e50..005cc23 100644
--- a/be/src/util/debug-util.h
+++ b/be/src/util/debug-util.h
@@ -108,21 +108,40 @@ std::string GetStackTrace();
 /// Returns the backend name in "host:port" form suitable for human consumption.
 std::string GetBackendString();
 
-/// Slow path implementing SleepIfSetInDebugOptions() for the case where 'query_options'
-/// is non-empty.
-void SleepIfSetInDebugOptionsImpl(
-    const TQueryOptions& query_options, const string& sleep_label);
-
-/// If sleep time is specified in the debug_action query option in the format
-/// <sleep_label>:<sleep_time_ms>, where <sleep_label> is a string and <sleep_time_ms>
-/// is an integer, and 'sleep_label' matches the one specified in the query option, then
-/// this methods extracts the corresponding <sleep_time_ms> and initiates a sleep for that
-/// many milliseconds.
-static inline void SleepIfSetInDebugOptions(
-    const TQueryOptions& query_options, const string& sleep_label) {
-  // Make sure this is very cheap if debug actions are not in use.
-  if (LIKELY(query_options.debug_action.empty())) return;
-  return SleepIfSetInDebugOptionsImpl(query_options, sleep_label);
+/// Tokenize 'debug_actions' into a list of tokenized rows, where columns are separated
+/// by ':' and rows by '|'. i.e. if debug_actions="a:b:c|x:y", then the returned
+/// structure is {{"a", "b", "c"}, {"x", "y"}}
+typedef std::list<std::vector<string>> DebugActionTokens;
+DebugActionTokens TokenizeDebugActions(const string& debug_actions);
+
+/// Tokenize 'action' which has an optional parameter separated by '@'. i.e. "x@y"
+/// becomes {"x", "y"} and "x" becomes {"x"}.
+std::vector<std::string> TokenizeDebugActionParams(const string& action);
+
+/// Slow path implementing DebugAction() for the case where
+/// 'query_options.debug_action' is non-empty.
+Status DebugActionImpl(
+    const TQueryOptions& query_options, const char* label) WARN_UNUSED_RESULT;
+
+/// If debug_action query option has a "global action" (i.e. not exec-node specific)
+/// and matches the given 'label', apply the the action. See ImpalaService.thrift for
+/// details of the format and available global actions. For ExecNode code, use
+/// ExecNode::ExecDebugAction() instead.
+WARN_UNUSED_RESULT static inline Status DebugAction(
+    const TQueryOptions& query_options, const char* label) {
+  if (LIKELY(query_options.debug_action.empty())) return Status::OK();
+  return DebugActionImpl(query_options, label);
+}
+
+/// Like DebugAction() but for use in contexts that can't safely propagate an error
+/// status. Debug action FAIL should not be used in these contexts and will be logged
+/// and ignored.
+static inline void DebugActionNoFail(
+    const TQueryOptions& query_options, const char* label) {
+  Status status = DebugAction(query_options, label);
+  if (!status.ok()) {
+    LOG(ERROR) << "Ignoring debug action failure: " << status.GetDetail();
+  }
 }
 
 // FILE_CHECKs are conditions that we expect to be true but could fail due to a malformed
diff --git a/common/thrift/ImpalaService.thrift b/common/thrift/ImpalaService.thrift
index 3114cfb..b4f48fa 100644
--- a/common/thrift/ImpalaService.thrift
+++ b/common/thrift/ImpalaService.thrift
@@ -83,7 +83,8 @@ enum TImpalaQueryOptions {
 
   // DEBUG ONLY:
   // Accepted formats:
-  // 1. "[<backend number>:]<node id>:<TExecNodePhase>:<TDebugAction>",
+  // 1. ExecNode actions
+  //  "[<instance idx>:]<node id>:<TExecNodePhase>:<TDebugAction>",
   //  the exec node with the given id will perform the specified action in the given
   //  phase. If the optional backend number (starting from 0) is specified, only that
   //  backend instance will perform the debug action, otherwise all backends will behave
@@ -91,11 +92,19 @@ enum TImpalaQueryOptions {
   //  If the string doesn't have the required format or if any of its components is
   //  invalid, the option is ignored.
   //
-  // 2. <sleep_label>:<sleep_time_ms>,
-  //  <sleep_label> is used as a string key that represents a location in the codebase
-  //  where sleep() is to be executed for <sleep_time_ms> milliseconds.
-  //  Available sleep_label : SLEEP_BEFORE_ADMISSION_MS,
-  //  SLEEP_AFTER_COORDINATOR_STARTS_MS, SLEEP_AFTER_ADMISSION_OUTCOME_MS
+  // 2. Global actions
+  //  "<global label>:<command>@<param0>@<param1>@...<paramN>",
+  //  global labels are marked in the code with DEBUG_ACTION*() macros.
+  //  Available global actions:
+  //  - SLEEP@<ms> will sleep for the 'ms' milliseconds.
+  //  - JITTER@<ms>[@<probability>] will sleep for a random amount of time between 0
+  //    and 'ms' milliseconds with the given probability. If <probability> is omitted,
+  //    it is 1.0.
+  //  - FAIL[@<probability>] returns an INTERNAL_ERROR status with the given
+  //    probability. If <probability> is omitted, it is 1.0.
+  //
+  // Only a single ExecNode action is allowed, but multiple global actions can be
+  // specified. To specify multiple actions, separate them with "|".
   DEBUG_ACTION,
 
   // If true, raise an error when the DEFAULT_ORDER_BY_LIMIT has been reached.
diff --git a/tests/custom_cluster/test_admission_controller.py b/tests/custom_cluster/test_admission_controller.py
index 57d0dc2..d6106ef 100644
--- a/tests/custom_cluster/test_admission_controller.py
+++ b/tests/custom_cluster/test_admission_controller.py
@@ -529,7 +529,7 @@ class TestAdmissionController(TestAdmissionControllerBase, HS2TestSuite):
     impalad = self.cluster.impalads[0]
     client = impalad.service.create_beeswax_client()
     try:
-      client.set_configuration_option("debug_action", "SLEEP_BEFORE_ADMISSION_MS:2000")
+      client.set_configuration_option("debug_action", "CRS_BEFORE_ADMISSION:SLEEP@2000")
       client.set_configuration_option("mem_limit", self.PROC_MEM_TEST_LIMIT + 1 )
       handle = client.execute_async("select 1")
       sleep(1)
@@ -538,15 +538,15 @@ class TestAdmissionController(TestAdmissionControllerBase, HS2TestSuite):
           "Ready to be Rejected but already cancelled, query id=")
       client.clear_configuration()
 
-      client.set_configuration_option("debug_action", "SLEEP_BEFORE_ADMISSION_MS:2000")
+      client.set_configuration_option("debug_action", "CRS_BEFORE_ADMISSION:SLEEP@2000")
       handle = client.execute_async("select 1")
       sleep(1)
       client.close_query(handle)
       self.assert_impalad_log_contains('INFO',
           "Ready to be Admitted immediately but already cancelled, query id=")
 
-      client.set_configuration_option("debug_action",
-          "SLEEP_AFTER_COORDINATOR_STARTS_MS:2000")
+      client.set_configuration_option(
+          "debug_action", "CRS_AFTER_COORD_STARTS:SLEEP@2000")
       handle = client.execute_async("select 1")
       sleep(1)
       client.close_query(handle)
@@ -555,8 +555,8 @@ class TestAdmissionController(TestAdmissionControllerBase, HS2TestSuite):
 
       client.clear_configuration()
       handle = client.execute_async("select sleep(10000)")
-      client.set_configuration_option("debug_action",
-          "SLEEP_AFTER_ADMISSION_OUTCOME_MS:2000")
+      client.set_configuration_option(
+          "debug_action", "AC_AFTER_ADMISSION_OUTCOME:SLEEP@2000")
       queued_query_handle = client.execute_async("select 1")
       sleep(1)
       assert client.get_state(queued_query_handle) == QueryState.COMPILED
diff --git a/tests/failure/test_failpoints.py b/tests/failure/test_failpoints.py
index 1f0c1c5..9f54257 100644
--- a/tests/failure/test_failpoints.py
+++ b/tests/failure/test_failpoints.py
@@ -103,6 +103,9 @@ class TestFailpoints(ImpalaTestSuite):
 
     for node_id in plan_node_ids:
       debug_action = '%d:%s:%s' % (node_id, location, FAILPOINT_ACTION_MAP[action])
+      # IMPALA-7046: add jitter to backend startup to exercise various failure paths.
+      debug_action += '|COORD_BEFORE_EXEC_RPC:JITTER@100@0.3'
+
       LOG.info('Current debug action: SET DEBUG_ACTION=%s' % debug_action)
       vector.get_value('exec_option')['debug_action'] = debug_action
 
diff --git a/tests/query_test/test_observability.py b/tests/query_test/test_observability.py
index 4e4bc25..19b47a3 100644
--- a/tests/query_test/test_observability.py
+++ b/tests/query_test/test_observability.py
@@ -89,8 +89,8 @@ class TestObservability(ImpalaTestSuite):
   def test_query_states(self):
     """Tests that the query profile shows expected query states."""
     query = "select count(*) from functional.alltypes"
-    handle = self.execute_query_async(query,
-        {"debug_action": "SLEEP_BEFORE_ADMISSION_MS:1000"})
+    handle = self.execute_query_async(
+        query, {"debug_action": "CRS_BEFORE_ADMISSION:SLEEP@1000"})
     # If ExecuteStatement() has completed and the query is paused in the admission control
     # phase, then the query must be in COMPILED state.
     profile = self.client.get_runtime_profile(handle)
@@ -124,8 +124,8 @@ class TestObservability(ImpalaTestSuite):
   def test_exec_summary(self):
     """Test that the exec summary is populated correctly in every query state"""
     query = "select count(*) from functional.alltypes"
-    handle = self.execute_query_async(query,
-        {"debug_action": "SLEEP_BEFORE_ADMISSION_MS:1000"})
+    handle = self.execute_query_async(
+        query, {"debug_action": "CRS_BEFORE_ADMISSION:SLEEP@1000"})
     # If ExecuteStatement() has completed and the query is paused in the admission control
     # phase, then the coordinator has not started yet and exec_summary should be empty.
     exec_summary = self.client.get_exec_summary(handle)


[impala] 02/13: IMPALA-7150: fixes jni frame scope

Posted by ta...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tarmstrong pushed a commit to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git

commit e9643393ec22a76de255c161bf55420ccad2824d
Author: Vuk Ercegovac <ve...@cloudera.com>
AuthorDate: Thu Jun 14 23:59:09 2018 -0700

    IMPALA-7150: fixes jni frame scope
    
    A previous change (https://gerrit.cloudera.org/#/c/9968/)
    reduced the time that a lib-cache entry was held when initializing
    a udf. It did so by introducing a new scope. However, that scope
    captured a jni frame, which resulted in an earlier frame pop
    than before. This change decouples the frame scope from the lib-cache
    scope so that the frame is popped at the end of the method (as before)
    instread of with the lib-cache scope.
    
    Testing:
    - core, asan tests pass
    
    Change-Id: I38d482dde6ed7f8857ae565bf62a8e923ffb0ae9
    Reviewed-on: http://gerrit.cloudera.org:8080/10746
    Reviewed-by: Impala Public Jenkins <im...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
 be/src/exprs/hive-udf-call.cc | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/be/src/exprs/hive-udf-call.cc b/be/src/exprs/hive-udf-call.cc
index b7715b7..22683ca 100644
--- a/be/src/exprs/hive-udf-call.cc
+++ b/be/src/exprs/hive-udf-call.cc
@@ -198,7 +198,10 @@ Status HiveUdfCall::OpenEvaluator(FunctionContext::FunctionStateScope scope,
   JNIEnv* env = getJNIEnv();
   if (env == NULL) return Status("Failed to get/create JVM");
 
+  // Add a scoped cleanup jni reference object. This cleans up local refs made below.
+  JniLocalFrame jni_frame;
   {
+    // Scoped handle for libCache entry.
     LibCacheEntryHandle handle;
     string local_location;
     RETURN_IF_ERROR(LibCache::instance()->GetLocalPath(fn_.hdfs_location,
@@ -219,12 +222,13 @@ Status HiveUdfCall::OpenEvaluator(FunctionContext::FunctionStateScope scope,
 
     jbyteArray ctor_params_bytes;
 
-    // Add a scoped cleanup jni reference object. This cleans up local refs made below.
-    JniLocalFrame jni_frame;
+    // Pushed frame will be popped when jni_frame goes out-of-scope.
     RETURN_IF_ERROR(jni_frame.push(env));
 
     RETURN_IF_ERROR(SerializeThriftMsg(env, &ctor_params, &ctor_params_bytes));
-    // Create the java executor object
+    // Create the java executor object. The jar referenced by the libCache handle
+    // is not needed after the next call, so it is safe for the handle to go
+    // out-of-scope after the java object is instantiated.
     jni_ctx->executor = env->NewObject(executor_cl_, executor_ctor_id_, ctor_params_bytes);
   }
   RETURN_ERROR_IF_EXC(env);


[impala] 08/13: IMPALA-5763: [DOCS] Warn against setting --logbufsecs to 0

Posted by ta...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tarmstrong pushed a commit to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git

commit f3761d449b5e0e4247a71334b43ae7d7fc3d4f7b
Author: Alex Rodoni <ar...@cloudera.com>
AuthorDate: Thu Jun 21 16:09:18 2018 -0700

    IMPALA-5763: [DOCS] Warn against setting --logbufsecs to 0
    
    Change-Id: I45d14e2ba601574cf76a4b739617b097f3e551aa
    Reviewed-on: http://gerrit.cloudera.org:8080/10790
    Reviewed-by: Tim Armstrong <ta...@cloudera.com>
    Reviewed-by: Lars Volker <lv...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
 docs/topics/impala_logging.xml | 57 ++++++++++++++++++++++++++++--------------
 1 file changed, 38 insertions(+), 19 deletions(-)

diff --git a/docs/topics/impala_logging.xml b/docs/topics/impala_logging.xml
index 6246ac6..22e149e 100644
--- a/docs/topics/impala_logging.xml
+++ b/docs/topics/impala_logging.xml
@@ -215,30 +215,49 @@ under the License.
       </p>
 
       <p>
-        Impala can automatically remove older unneeded log files, a feature known as <term>log rotation</term>.
-<!-- Another instance of the text also used in impala_new_features.xml
-             and impala_fixed_issues.xml. (Just took out the word "new"
-             and added the reference to the starting release.)
-             At this point, a conref is definitely in the cards. -->
+        Impala can automatically remove older unneeded log files, a feature
+        known as <term>log rotation</term>.
       </p>
 
       <p>
-        In Impala 2.2 and higher, the <codeph>--max_log_files</codeph> configuration option specifies how many log
-        files to keep at each severity level. You can specify an appropriate setting for each Impala-related daemon
-        (<cmdname>impalad</cmdname>, <cmdname>statestored</cmdname>, and <cmdname>catalogd</cmdname>). The default
-        value is 10, meaning that Impala preserves the latest 10 log files for each severity level
-        (<codeph>INFO</codeph>, <codeph>WARNING</codeph>, <codeph>ERROR</codeph>, and <codeph>FATAL</codeph>).
-        Impala checks to see if any old logs need to be removed based on the interval specified in the
-        <codeph>logbufsecs</codeph> setting, every 5 seconds by default.
+        In Impala 2.2 and higher, the <codeph>--max_log_files</codeph>
+        configuration option specifies how many log files to keep at each
+        severity level (<codeph>INFO</codeph>, <codeph>WARNING</codeph>,
+          <codeph>ERROR</codeph>, and <codeph>FATAL</codeph>). You can specify
+        an appropriate setting for each Impala-related daemon
+          (<cmdname>impalad</cmdname>, <cmdname>statestored</cmdname>, and
+          <cmdname>catalogd</cmdname>).
+        <ul>
+          <li>
+            A value of 0 preserves all log files, in which case you would set
+            up set up manual log rotation using your Linux tool or technique of
+            choice.
+          </li>
+          <li>
+            A value of 1 preserves only the very latest log file.
+          </li>
+          <li>
+            The default value is 10.
+          </li>
+        </ul>
+      </p>
+      <p>
+        Impala checks to see if any old logs need to be removed based on the
+        interval specified in the <codeph>--logbufsecs</codeph> setting, every 5
+        seconds by default.
+      </p>
+      <p>
+        For some log levels, Impala logs are first temporarily buffered in
+        memory and only written to disk periodically. The
+          <codeph>--logbufsecs</codeph> setting controls the maximum time that
+        log messages are buffered for. For example, with the default value of 5
+        seconds, there may be up to a 5 second delay before a logged message
+        shows up in the log file.
       </p>
-
-<!-- This extra detail only appears here. Consider if it's worth including it
-           in the conref so people don't need to follow a link just for a couple of
-           minor factoids. -->
-
       <p>
-        A value of 0 preserves all log files, in which case you would set up set up manual log rotation using your
-        Linux tool or technique of choice. A value of 1 preserves only the very latest log file.
+        It is not recommended that you set <codeph>--logbufsecs</codeph> to 0
+        as the setting makes the Impala daemon to spin in the thread that tries
+        to delete old log files.
       </p>
 
     </conbody>


[impala] 13/13: IMPALA-7191: don't call srand() at random times

Posted by ta...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tarmstrong pushed a commit to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git

commit 23922ddf318f19f4b2cd481a745d20d0ac98ca2f
Author: Dan Hecht <dh...@cloudera.com>
AuthorDate: Wed Jun 20 15:32:16 2018 -0700

    IMPALA-7191: don't call srand() at random times
    
    Instead, call it from the daemons' main(), and remove the
    calls that happen at random time during the lifetime of the
    daemons. Doesn't attempt to cleanup the backend unit tests
    which can happen separately or not at all.
    
    Change-Id: Iaf0ef5a0e842ebdcdb6d7355302e68fb0bc7ef5f
    Reviewed-on: http://gerrit.cloudera.org:8080/10778
    Reviewed-by: Impala Public Jenkins <im...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
 be/src/common/init.cc                     | 2 ++
 be/src/exec/hdfs-table-sink.cc            | 7 -------
 be/src/runtime/data-stream-sender.cc      | 1 -
 be/src/runtime/krpc-data-stream-sender.cc | 1 -
 be/src/testutil/fault-injection-util.cc   | 2 --
 5 files changed, 2 insertions(+), 11 deletions(-)

diff --git a/be/src/common/init.cc b/be/src/common/init.cc
index 9daaf5c..92b6dcc 100644
--- a/be/src/common/init.cc
+++ b/be/src/common/init.cc
@@ -172,6 +172,8 @@ static void PauseMonitorLoop() {
 
 void impala::InitCommonRuntime(int argc, char** argv, bool init_jvm,
     TestInfo::Mode test_mode) {
+  srand(time(NULL));
+
   CpuInfo::Init();
   DiskInfo::Init();
   MemInfo::Init();
diff --git a/be/src/exec/hdfs-table-sink.cc b/be/src/exec/hdfs-table-sink.cc
index 3b7dc0f..b6de7cf 100644
--- a/be/src/exec/hdfs-table-sink.cc
+++ b/be/src/exec/hdfs-table-sink.cc
@@ -99,13 +99,6 @@ Status HdfsTableSink::Prepare(RuntimeState* state, MemTracker* parent_mem_tracke
       state->obj_pool(), expr_perm_pool_.get(), expr_results_pool_.get(),
       &partition_key_expr_evals_));
 
-  // TODO: Consider a system-wide random number generator, initialised in a single place.
-  ptime now = microsec_clock::local_time();
-  long seed = (now.time_of_day().seconds() * 1000)
-    + (now.time_of_day().total_microseconds() / 1000);
-  VLOG_QUERY << "Random seed: " << seed;
-  srand(seed);
-
   // Resolve table id and set input tuple descriptor.
   table_desc_ = static_cast<const HdfsTableDescriptor*>(
       state->desc_tbl().GetTableDescriptor(table_id_));
diff --git a/be/src/runtime/data-stream-sender.cc b/be/src/runtime/data-stream-sender.cc
index 7d0766d..a37c3c1 100644
--- a/be/src/runtime/data-stream-sender.cc
+++ b/be/src/runtime/data-stream-sender.cc
@@ -361,7 +361,6 @@ DataStreamSender::DataStreamSender(int sender_id, const RowDescriptor* row_desc,
   if (partition_type_ == TPartitionType::UNPARTITIONED
       || partition_type_ == TPartitionType::RANDOM) {
     // Randomize the order we open/transmit to channels to avoid thundering herd problems.
-    srand(reinterpret_cast<uint64_t>(this));
     random_shuffle(channels_.begin(), channels_.end());
   }
 }
diff --git a/be/src/runtime/krpc-data-stream-sender.cc b/be/src/runtime/krpc-data-stream-sender.cc
index 74eb129..b362758 100644
--- a/be/src/runtime/krpc-data-stream-sender.cc
+++ b/be/src/runtime/krpc-data-stream-sender.cc
@@ -601,7 +601,6 @@ KrpcDataStreamSender::KrpcDataStreamSender(int sender_id, const RowDescriptor* r
   if (partition_type_ == TPartitionType::UNPARTITIONED ||
       partition_type_ == TPartitionType::RANDOM) {
     // Randomize the order we open/transmit to channels to avoid thundering herd problems.
-    srand(reinterpret_cast<uint64_t>(this));
     random_shuffle(channels_.begin(), channels_.end());
   }
 }
diff --git a/be/src/testutil/fault-injection-util.cc b/be/src/testutil/fault-injection-util.cc
index 925fcd9..cf9265c 100644
--- a/be/src/testutil/fault-injection-util.cc
+++ b/be/src/testutil/fault-injection-util.cc
@@ -45,8 +45,6 @@ int32_t FaultInjectionUtil::GetTargetRPCType() {
 }
 
 void FaultInjectionUtil::InjectRpcDelay(RpcCallType my_type) {
-  std::random_device rd;
-  srand(rd());
   int32_t delay_ms = FLAGS_fault_injection_rpc_delay_ms;
   if (delay_ms == 0) return;
   int32_t target_rpc_type = GetTargetRPCType();


[impala] 10/13: IMPALA-7140 (part 3): load partitions for FS tables

Posted by ta...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tarmstrong pushed a commit to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git

commit 4a279e1bc430b5204e59e73b3b8fb68a0b5e64ab
Author: Todd Lipcon <to...@cloudera.com>
AuthorDate: Tue Jun 12 20:16:07 2018 -0700

    IMPALA-7140 (part 3): load partitions for FS tables
    
    This implements the loading of partitions from the HMS for FS-based
    tables. The LocalPartitionSpec class implements PrunablePartition based
    on parsing the partition names returned from the HMS. After partitions
    are pruned, the remaining partitions can be loaded by name.
    
    With this patch, I am able to connect to an impalad running with
    --use_local_catalog and issue 'show partitions functional.alltypes' with
    the expected results.
    
    A new unit test is added which shares some code with CatalogTest to
    ensure that partitions can be loaded and parsed properly.
    
    Testing partition pruning via end-to-end planning is not quite
    supported yet: we need to implement 'toThriftDescriptor()' before we can
    run those end-to-end tests.
    
    Change-Id: Iddf2edbd6bdc0684560b2ecca9c4c6b6819ef1d3
    Reviewed-on: http://gerrit.cloudera.org:8080/10713
    Reviewed-by: Vuk Ercegovac <ve...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
 .../org/apache/impala/catalog/FeCatalogUtils.java  | 100 +++++++++++
 .../org/apache/impala/catalog/HdfsPartition.java   |  60 +------
 .../java/org/apache/impala/catalog/HdfsTable.java  |  24 +--
 .../apache/impala/catalog/PartitionStatsUtil.java  |  19 ++-
 .../impala/catalog/local/DirectMetaProvider.java   |  64 +++++++
 .../impala/catalog/local/LocalFsPartition.java     | 185 +++++++++++++++++++++
 .../apache/impala/catalog/local/LocalFsTable.java  | 185 +++++++++++++++++++--
 .../impala/catalog/local/LocalPartitionSpec.java   |  71 ++++++++
 .../apache/impala/catalog/local/LocalTable.java    |   4 +-
 .../apache/impala/catalog/local/MetaProvider.java  |  17 ++
 .../apache/impala/service/CatalogOpExecutor.java   |  21 +--
 .../java/org/apache/impala/util/MetaStoreUtil.java |  21 +++
 .../org/apache/impala/catalog/CatalogTest.java     |  13 +-
 .../impala/catalog/local/LocalCatalogTest.java     |  31 +++-
 14 files changed, 707 insertions(+), 108 deletions(-)

diff --git a/fe/src/main/java/org/apache/impala/catalog/FeCatalogUtils.java b/fe/src/main/java/org/apache/impala/catalog/FeCatalogUtils.java
index 7d811c2..80ab246 100644
--- a/fe/src/main/java/org/apache/impala/catalog/FeCatalogUtils.java
+++ b/fe/src/main/java/org/apache/impala/catalog/FeCatalogUtils.java
@@ -19,18 +19,32 @@ package org.apache.impala.catalog;
 
 import java.util.Collection;
 import java.util.Collections;
+import java.util.List;
 import java.util.Map;
 
+import org.apache.hadoop.hive.common.FileUtils;
 import org.apache.hadoop.hive.common.StatsSetupConst;
 import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.impala.analysis.Expr;
+import org.apache.impala.analysis.LiteralExpr;
+import org.apache.impala.analysis.NullLiteral;
+import org.apache.impala.analysis.PartitionKeyValue;
+import org.apache.impala.analysis.ToSqlUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
 
 /**
  * Static utility functions shared between FeCatalog implementations.
  */
 public abstract class FeCatalogUtils {
+  private final static Logger LOG = LoggerFactory.getLogger(FeCatalogUtils.class);
+
   /**
    * Gets the ColumnType from the given FieldSchema by using Impala's SqlParser.
    *
@@ -148,4 +162,90 @@ public abstract class FeCatalogUtils {
       FeFsTable table) {
     return table.loadPartitions(table.getPartitionIds());
   }
+
+  /**
+   * Parse the partition key values out of their stringified format used by HMS.
+   */
+  public static List<LiteralExpr> parsePartitionKeyValues(FeFsTable table,
+      List<String> hmsPartitionValues) throws CatalogException {
+    Preconditions.checkArgument(
+        hmsPartitionValues.size() == table.getNumClusteringCols(),
+        "Cannot parse partition values %s for table %s: " +
+        "expected %s values but got %s",
+        hmsPartitionValues, table.getFullName(),
+        table.getNumClusteringCols(), hmsPartitionValues.size());
+    List<LiteralExpr> keyValues = Lists.newArrayList();
+    for (String partitionKey: hmsPartitionValues) {
+      Type type = table.getColumns().get(keyValues.size()).getType();
+      // Deal with Hive's special NULL partition key.
+      if (partitionKey.equals(table.getNullPartitionKeyValue())) {
+        keyValues.add(NullLiteral.create(type));
+      } else {
+        try {
+          keyValues.add(LiteralExpr.create(partitionKey, type));
+        } catch (Exception ex) {
+          LOG.warn("Failed to create literal expression of type: " + type, ex);
+          throw new CatalogException("Invalid partition key value of type: " + type,
+              ex);
+        }
+      }
+    }
+    for (Expr v: keyValues) v.analyzeNoThrow(null);
+    return keyValues;
+  }
+
+  /**
+   * Return a partition name formed by concatenating partition keys and their values,
+   * compatible with the way Hive names partitions. Reuses Hive's
+   * org.apache.hadoop.hive.common.FileUtils.makePartName() function to build the name
+   * string because there are a number of special cases for how partition names are URL
+   * escaped.
+   *
+   * TODO: this could be a default method in FeFsPartition in Java 8.
+   */
+  public static String getPartitionName(FeFsPartition partition) {
+    FeFsTable table = partition.getTable();
+    List<String> partitionCols = Lists.newArrayList();
+    for (int i = 0; i < table.getNumClusteringCols(); ++i) {
+      partitionCols.add(table.getColumns().get(i).getName());
+    }
+
+    return FileUtils.makePartName(
+        partitionCols, getPartitionValuesAsStrings(partition, true));
+  }
+
+  // TODO: this could be a default method in FeFsPartition in Java 8.
+  public static List<String> getPartitionValuesAsStrings(
+      FeFsPartition partition, boolean mapNullsToHiveKey) {
+    List<String> ret = Lists.newArrayList();
+    for (LiteralExpr partValue: partition.getPartitionValues()) {
+      if (mapNullsToHiveKey) {
+        ret.add(PartitionKeyValue.getPartitionKeyValueString(
+                partValue, partition.getTable().getNullPartitionKeyValue()));
+      } else {
+        ret.add(partValue.getStringValue());
+      }
+    }
+    return ret;
+  }
+
+  // TODO: this could be a default method in FeFsPartition in Java 8.
+  public static String getConjunctSqlForPartition(FeFsPartition part) {
+    List<String> partColSql = Lists.newArrayList();
+    for (Column partCol: part.getTable().getClusteringColumns()) {
+      partColSql.add(ToSqlUtils.getIdentSql(partCol.getName()));
+    }
+
+    List<String> conjuncts = Lists.newArrayList();
+    for (int i = 0; i < partColSql.size(); ++i) {
+      LiteralExpr partVal = part.getPartitionValues().get(i);
+      String partValSql = partVal.toSql();
+      if (partVal instanceof NullLiteral || partValSql.isEmpty()) {
+        conjuncts.add(partColSql.get(i) + " IS NULL");
+      } else {
+        conjuncts.add(partColSql.get(i) + "=" + partValSql);
+      }
+    }
+    return "(" + Joiner.on(" AND " ).join(conjuncts) + ")";
+  }
 }
diff --git a/fe/src/main/java/org/apache/impala/catalog/HdfsPartition.java b/fe/src/main/java/org/apache/impala/catalog/HdfsPartition.java
index 12b4a59..26f8c30 100644
--- a/fe/src/main/java/org/apache/impala/catalog/HdfsPartition.java
+++ b/fe/src/main/java/org/apache/impala/catalog/HdfsPartition.java
@@ -36,7 +36,6 @@ import org.apache.impala.analysis.NullLiteral;
 import org.apache.impala.analysis.PartitionKeyValue;
 import org.apache.impala.analysis.ToSqlUtils;
 import org.apache.impala.common.FileSystemUtil;
-import org.apache.impala.common.ImpalaException;
 import org.apache.impala.common.Pair;
 import org.apache.impala.common.Reference;
 import org.apache.impala.fb.FbCompression;
@@ -447,60 +446,23 @@ public class HdfsPartition implements FeFsPartition, PrunablePartition {
     return FileSystemUtil.isPathCacheable(new Path(getLocation()));
   }
 
-  /**
-   * Return a partition name formed by concatenating partition keys and their values,
-   * compatible with the way Hive names partitions. Reuses Hive's
-   * org.apache.hadoop.hive.common.FileUtils.makePartName() function to build the name
-   * string because there are a number of special cases for how partition names are URL
-   * escaped.
-   * TODO: Consider storing the PartitionKeyValue in HdfsPartition. It would simplify
-   * this code would be useful in other places, such as fromThrift().
-   */
   @Override // FeFsPartition
   public String getPartitionName() {
-    List<String> partitionCols = Lists.newArrayList();
-    for (int i = 0; i < getTable().getNumClusteringCols(); ++i) {
-      partitionCols.add(getTable().getColumns().get(i).getName());
-    }
-
-    return org.apache.hadoop.hive.common.FileUtils.makePartName(
-        partitionCols, getPartitionValuesAsStrings(true));
+    // TODO: Consider storing the PartitionKeyValue in HdfsPartition. It would simplify
+    // this code would be useful in other places, such as fromThrift().
+    return FeCatalogUtils.getPartitionName(this);
   }
 
   @Override
   public List<String> getPartitionValuesAsStrings(boolean mapNullsToHiveKey) {
-    List<String> ret = Lists.newArrayList();
-    for (LiteralExpr partValue: getPartitionValues()) {
-      if (mapNullsToHiveKey) {
-        ret.add(PartitionKeyValue.getPartitionKeyValueString(
-                partValue, getTable().getNullPartitionKeyValue()));
-      } else {
-        ret.add(partValue.getStringValue());
-      }
-    }
-    return ret;
+    return FeCatalogUtils.getPartitionValuesAsStrings(this, mapNullsToHiveKey);
   }
 
   @Override // FeFsPartition
   public String getConjunctSql() {
     // TODO: Remove this when the TODO elsewhere in this file to save and expose the
     // list of TPartitionKeyValues has been resolved.
-    List<String> partColSql = Lists.newArrayList();
-    for (Column partCol: getTable().getClusteringColumns()) {
-      partColSql.add(ToSqlUtils.getIdentSql(partCol.getName()));
-    }
-
-    List<String> conjuncts = Lists.newArrayList();
-    for (int i = 0; i < partColSql.size(); ++i) {
-      LiteralExpr partVal = getPartitionValues().get(i);
-      String partValSql = partVal.toSql();
-      if (partVal instanceof NullLiteral || partValSql.isEmpty()) {
-        conjuncts.add(partColSql.get(i) + " IS NULL");
-      } else {
-        conjuncts.add(partColSql.get(i) + "=" + partValSql);
-      }
-    }
-    return "(" + Joiner.on(" AND " ).join(conjuncts) + ")";
+    return FeCatalogUtils.getConjunctSqlForPartition(this);
   }
 
   /**
@@ -565,18 +527,14 @@ public class HdfsPartition implements FeFsPartition, PrunablePartition {
 
   @Override // FeFsPartition
   public TPartitionStats getPartitionStats() {
-    try {
-      return PartitionStatsUtil.partStatsFromParameters(hmsParameters_);
-    } catch (ImpalaException e) {
-      LOG.warn("Could not deserialise incremental stats state for " + getPartitionName() +
-          ", consider DROP INCREMENTAL STATS ... PARTITION ... and recomputing " +
-          "incremental stats for this table.");
-      return null;
-    }
+    return PartitionStatsUtil.getPartStatsOrWarn(this);
   }
 
   @Override // FeFsPartition
   public boolean hasIncrementalStats() {
+    // TODO: performance of this could improve substantially, since
+    // getPartitionStats() performs a bunch of expensive deserialization,
+    // only to end up throwing away the result.
     TPartitionStats partStats = getPartitionStats();
     return partStats != null && partStats.intermediate_col_stats != null;
   }
diff --git a/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java b/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
index b0b4387..e6c34bc 100644
--- a/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
+++ b/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
@@ -52,7 +52,6 @@ import org.apache.hadoop.hive.metastore.api.Partition;
 import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
 import org.apache.hadoop.hive.serde.serdeConstants;
 import org.apache.impala.analysis.ColumnDef;
-import org.apache.impala.analysis.Expr;
 import org.apache.impala.analysis.LiteralExpr;
 import org.apache.impala.analysis.NullLiteral;
 import org.apache.impala.analysis.NumericLiteral;
@@ -1047,27 +1046,12 @@ public class HdfsTable extends Table implements FeFsTable {
       throws CatalogException {
     HdfsStorageDescriptor fileFormatDescriptor =
         HdfsStorageDescriptor.fromStorageDescriptor(this.name_, storageDescriptor);
-    List<LiteralExpr> keyValues = Lists.newArrayList();
+    List<LiteralExpr> keyValues;
     if (msPartition != null) {
-      // Load key values
-      for (String partitionKey: msPartition.getValues()) {
-        Type type = getColumns().get(keyValues.size()).getType();
-        // Deal with Hive's special NULL partition key.
-        if (partitionKey.equals(nullPartitionKeyValue_)) {
-          keyValues.add(NullLiteral.create(type));
-        } else {
-          try {
-            keyValues.add(LiteralExpr.create(partitionKey, type));
-          } catch (Exception ex) {
-            LOG.warn("Failed to create literal expression of type: " + type, ex);
-            throw new CatalogException("Invalid partition key value of type: " + type,
-                ex);
-          }
-        }
-      }
-      for (Expr v: keyValues) v.analyzeNoThrow(null);
+      keyValues = FeCatalogUtils.parsePartitionKeyValues(this, msPartition.getValues());
+    } else {
+      keyValues = Collections.emptyList();
     }
-
     Path partDirPath = new Path(storageDescriptor.getLocation());
     try {
       FileSystem fs = partDirPath.getFileSystem(CONF);
diff --git a/fe/src/main/java/org/apache/impala/catalog/PartitionStatsUtil.java b/fe/src/main/java/org/apache/impala/catalog/PartitionStatsUtil.java
index 4444de6..c77ac91 100644
--- a/fe/src/main/java/org/apache/impala/catalog/PartitionStatsUtil.java
+++ b/fe/src/main/java/org/apache/impala/catalog/PartitionStatsUtil.java
@@ -50,11 +50,28 @@ public class PartitionStatsUtil {
   private final static Logger LOG = LoggerFactory.getLogger(PartitionStatsUtil.class);
 
   /**
+   * Get the partition stats from the given partition, or null if no stats
+   * are available. If stats are present but cannot be parsed, logs a warning
+   * and returns null.
+   */
+  public static TPartitionStats getPartStatsOrWarn(FeFsPartition part) {
+    try {
+      return partStatsFromParameters(part.getParameters());
+    } catch (ImpalaException e) {
+      LOG.warn("Could not deserialise incremental stats state for " +
+          part.getPartitionName() +
+          ", consider DROP INCREMENTAL STATS ... PARTITION ... and recomputing " +
+          "incremental stats for this table.");
+      return null;
+    }
+  }
+
+  /**
    * Reconstructs a TPartitionStats object from its serialised form in the given parameter
    * map. Returns null if no stats are serialised, and throws an exception if there was an
    * error during deserialisation.
    */
-  public static TPartitionStats partStatsFromParameters(
+  private static TPartitionStats partStatsFromParameters(
       Map<String, String> hmsParameters) throws ImpalaException {
     if (hmsParameters == null) return null;
     String numChunksStr = hmsParameters.get(INCREMENTAL_STATS_NUM_CHUNKS);
diff --git a/fe/src/main/java/org/apache/impala/catalog/local/DirectMetaProvider.java b/fe/src/main/java/org/apache/impala/catalog/local/DirectMetaProvider.java
index ac86bfd..e09f031 100644
--- a/fe/src/main/java/org/apache/impala/catalog/local/DirectMetaProvider.java
+++ b/fe/src/main/java/org/apache/impala/catalog/local/DirectMetaProvider.java
@@ -17,9 +17,15 @@
 
 package org.apache.impala.catalog.local;
 
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.hadoop.hive.common.FileUtils;
 import org.apache.hadoop.hive.metastore.api.Database;
 import org.apache.hadoop.hive.metastore.api.MetaException;
 import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.Partition;
 import org.apache.hadoop.hive.metastore.api.Table;
 import org.apache.hadoop.hive.metastore.api.UnknownDBException;
 import org.apache.impala.catalog.MetaStoreClientPool;
@@ -29,7 +35,10 @@ import org.apache.impala.thrift.TBackendGflags;
 import org.apache.impala.util.MetaStoreUtil;
 import org.apache.thrift.TException;
 
+import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Maps;
 
 /**
  * Metadata provider which calls out directly to the source systems
@@ -88,4 +97,59 @@ class DirectMetaProvider implements MetaProvider {
       return MetaStoreUtil.getNullPartitionKeyValue(c.getHiveClient());
     }
   }
+
+  @Override
+  public List<String> loadPartitionNames(String dbName, String tableName)
+      throws MetaException, TException {
+    try (MetaStoreClient c = msClientPool_.getClient()) {
+      return c.getHiveClient().listPartitionNames(dbName, tableName,
+          /*max_parts=*/(short)-1);
+    }
+  }
+
+  @Override
+  public Map<String, Partition> loadPartitionsByNames(
+      String dbName, String tableName, List<String> partitionColumnNames,
+      List<String> partitionNames) throws MetaException, TException {
+    Preconditions.checkNotNull(dbName);
+    Preconditions.checkNotNull(tableName);
+    Preconditions.checkArgument(!partitionColumnNames.isEmpty());
+    Preconditions.checkNotNull(partitionNames);
+
+    Map<String, Partition> ret = Maps.newHashMapWithExpectedSize(
+        partitionNames.size());
+    if (partitionNames.isEmpty()) return ret;
+
+    // Fetch the partitions.
+    List<Partition> parts;
+    try (MetaStoreClient c = msClientPool_.getClient()) {
+      parts = MetaStoreUtil.fetchPartitionsByName(
+          c.getHiveClient(), partitionNames, dbName, tableName);
+    }
+
+    // HMS may return fewer partition objects than requested, and the
+    // returned partition objects don't carry enough information to get their
+    // names. So, we map the returned partitions back to the requested names
+    // using the passed-in partition column names.
+    Set<String> namesSet = ImmutableSet.copyOf(partitionNames);
+    for (Partition p: parts) {
+      List<String> vals = p.getValues();
+      if (vals.size() != partitionColumnNames.size()) {
+        throw new MetaException("Unexpected number of partition values for " +
+          "partition " + vals + " (expected " + partitionColumnNames.size() + ")");
+      }
+      String partName = FileUtils.makePartName(partitionColumnNames, p.getValues());
+      if (!namesSet.contains(partName)) {
+        throw new MetaException("HMS returned unexpected partition " + partName +
+            " which was not requested. Requested: " + namesSet);
+      }
+      Partition existing = ret.put(partName, p);
+      if (existing != null) {
+        throw new MetaException("HMS returned multiple partitions with name " +
+            partName);
+      }
+    }
+
+    return ret;
+  }
 }
diff --git a/fe/src/main/java/org/apache/impala/catalog/local/LocalFsPartition.java b/fe/src/main/java/org/apache/impala/catalog/local/LocalFsPartition.java
new file mode 100644
index 0000000..c33b8a2
--- /dev/null
+++ b/fe/src/main/java/org/apache/impala/catalog/local/LocalFsPartition.java
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.impala.catalog.local;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.impala.analysis.LiteralExpr;
+import org.apache.impala.catalog.FeCatalogUtils;
+import org.apache.impala.catalog.FeFsPartition;
+import org.apache.impala.catalog.FeFsTable;
+import org.apache.impala.catalog.HdfsFileFormat;
+import org.apache.impala.catalog.HdfsPartition.FileDescriptor;
+import org.apache.impala.catalog.HdfsStorageDescriptor;
+import org.apache.impala.catalog.HdfsStorageDescriptor.InvalidStorageDescriptorException;
+import org.apache.impala.catalog.PartitionStatsUtil;
+import org.apache.impala.thrift.TAccessLevel;
+import org.apache.impala.thrift.TPartitionStats;
+
+import com.google.common.base.Preconditions;
+
+public class LocalFsPartition implements FeFsPartition {
+  private final LocalFsTable table_;
+  private final LocalPartitionSpec spec_;
+  private final Partition msPartition_;
+
+  public LocalFsPartition(LocalFsTable table, LocalPartitionSpec spec,
+      Partition msPartition) {
+    table_ = Preconditions.checkNotNull(table);
+    spec_ = Preconditions.checkNotNull(spec);
+    msPartition_ = Preconditions.checkNotNull(msPartition);
+  }
+
+  @Override
+  public String getPartitionName() {
+    return FeCatalogUtils.getPartitionName(this);
+  }
+
+  @Override
+  public long getId() {
+    return spec_.getId();
+  }
+
+  @Override
+  public FeFsTable getTable() {
+    return table_;
+  }
+
+  @Override
+  public List<FileDescriptor> getFileDescriptors() {
+    // TODO(todd): implement me
+    return Collections.emptyList();
+  }
+
+  @Override
+  public boolean hasFileDescriptors() {
+    // TODO Auto-generated method stub
+    return false;
+  }
+
+  @Override
+  public int getNumFileDescriptors() {
+    // TODO Auto-generated method stub
+    return 0;
+  }
+
+  @Override
+  public String getLocation() {
+    return msPartition_.getSd().getLocation();
+  }
+
+  @Override
+  public Path getLocationPath() {
+    return new Path(getLocation());
+  }
+
+  @Override
+  public TAccessLevel getAccessLevel() {
+    // TODO(todd): implement me
+    return TAccessLevel.READ_ONLY;
+  }
+
+  @Override
+  public boolean isCacheable() {
+    // TODO Auto-generated method stub
+    return false;
+  }
+
+  @Override
+  public boolean isMarkedCached() {
+    // TODO Auto-generated method stub
+    return false;
+  }
+
+  @Override
+  public HdfsStorageDescriptor getInputFormatDescriptor() {
+    try {
+      // TODO(todd): should we do this in the constructor to avoid having to worry
+      // about throwing an exception from this getter? The downside is that then
+      // the object would end up long-lived, whereas its actual usage is short-lived.
+      return HdfsStorageDescriptor.fromStorageDescriptor(table_.getName(),
+              msPartition_.getSd());
+    } catch (InvalidStorageDescriptorException e) {
+      throw new LocalCatalogException(String.format(
+          "Invalid input format descriptor for partition %s of table %s",
+          getPartitionName(), table_.getFullName()), e);
+    }
+  }
+
+  @Override
+  public HdfsFileFormat getFileFormat() {
+    return getInputFormatDescriptor().getFileFormat();
+  }
+
+  @Override
+  public TPartitionStats getPartitionStats() {
+    // TODO(todd): after HIVE-19715 is complete, we should defer loading these
+    // stats until requested. Even prior to that, we should consider caching them
+    // separately to increase effective cache capacity.
+    return PartitionStatsUtil.getPartStatsOrWarn(this);
+  }
+
+  @Override
+  public boolean hasIncrementalStats() {
+    // TODO(todd): copy-paste from HdfsPartition
+    // TODO(todd): as in the equivalent method in HdfsPartition, this is
+    // expensive because it deserializes the stats completely.
+    TPartitionStats partStats = getPartitionStats();
+    return partStats != null && partStats.intermediate_col_stats != null;
+  }
+
+  @Override
+  public long getSize() {
+    // TODO Auto-generated method stub
+    return 0;
+  }
+
+  @Override
+  public long getNumRows() {
+    return FeCatalogUtils.getRowCount(msPartition_.getParameters());
+  }
+
+  @Override
+  public String getConjunctSql() {
+    return FeCatalogUtils.getConjunctSqlForPartition(this);
+  }
+
+  @Override
+  public List<String> getPartitionValuesAsStrings(boolean mapNullsToHiveKey) {
+    return FeCatalogUtils.getPartitionValuesAsStrings(this, mapNullsToHiveKey);
+  }
+
+  @Override
+  public List<LiteralExpr> getPartitionValues() {
+    return spec_.getPartitionValues();
+  }
+
+  @Override
+  public LiteralExpr getPartitionValue(int pos) {
+    return spec_.getPartitionValues().get(pos);
+  }
+
+  @Override
+  public Map<String, String> getParameters() {
+    return msPartition_.getParameters();
+  }
+}
diff --git a/fe/src/main/java/org/apache/impala/catalog/local/LocalFsTable.java b/fe/src/main/java/org/apache/impala/catalog/local/LocalFsTable.java
index b6ab559..352655c 100644
--- a/fe/src/main/java/org/apache/impala/catalog/local/LocalFsTable.java
+++ b/fe/src/main/java/org/apache/impala/catalog/local/LocalFsTable.java
@@ -17,6 +17,7 @@
 
 package org.apache.impala.catalog.local;
 
+import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashSet;
@@ -25,8 +26,11 @@ import java.util.Map;
 import java.util.Set;
 import java.util.TreeMap;
 
+import org.apache.hadoop.hive.metastore.api.Partition;
 import org.apache.impala.analysis.LiteralExpr;
+import org.apache.impala.analysis.NullLiteral;
 import org.apache.impala.catalog.CatalogException;
+import org.apache.impala.catalog.Column;
 import org.apache.impala.catalog.FeFsPartition;
 import org.apache.impala.catalog.FeFsTable;
 import org.apache.impala.catalog.HdfsTable;
@@ -36,8 +40,36 @@ import org.apache.impala.thrift.TNetworkAddress;
 import org.apache.impala.thrift.TPartitionKeyValue;
 import org.apache.impala.thrift.TResultSet;
 import org.apache.impala.util.ListMap;
+import org.apache.thrift.TException;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
 
 public class LocalFsTable extends LocalTable implements FeFsTable {
+  /**
+   * Map from partition ID to partition spec.
+   *
+   * Set by loadPartitionSpecs().
+   */
+  ImmutableMap<Long, LocalPartitionSpec> partitionSpecs_;
+
+  /**
+   * For each partition column, a map from value to the set of partition IDs
+   * having that value.
+   *
+   * Set by loadPartitionValueMap().
+   */
+  private ArrayList<TreeMap<LiteralExpr, HashSet<Long>>> partitionValueMap_;
+
+  /**
+   * For each partition column, the set of partition IDs having a NULL value
+   * for that column.
+   *
+   * Set by loadPartitionValueMap().
+   */
+  private ArrayList<HashSet<Long>> nullPartitionIds_;
+
   public LocalFsTable(LocalDb db, String tblName, SchemaInfo schemaInfo) {
     super(db, tblName, schemaInfo);
   }
@@ -120,38 +152,167 @@ public class LocalFsTable extends LocalTable implements FeFsTable {
 
   @Override
   public Collection<? extends PrunablePartition> getPartitions() {
-    // TODO(todd): implement me
-    return Collections.emptyList();
+    loadPartitionSpecs();
+    return partitionSpecs_.values();
   }
 
   @Override
   public Set<Long> getPartitionIds() {
-    // TODO(todd): implement me
-    return Collections.emptySet();
+    loadPartitionSpecs();
+    return partitionSpecs_.keySet();
   }
 
   @Override
   public Map<Long, ? extends PrunablePartition> getPartitionMap() {
-    // TODO(todd): implement me
-    return Collections.emptyMap();
+    loadPartitionSpecs();
+    return partitionSpecs_;
   }
 
   @Override
   public TreeMap<LiteralExpr, HashSet<Long>> getPartitionValueMap(int col) {
-    // TODO(todd): implement me
-    return new TreeMap<>();
+    loadPartitionValueMap();
+    return partitionValueMap_.get(col);
   }
 
   @Override
   public Set<Long> getNullPartitionIds(int colIdx) {
-    // TODO(todd): implement me
-    return Collections.emptySet();
+    loadPartitionValueMap();
+    return nullPartitionIds_.get(colIdx);
   }
 
   @Override
   public List<? extends FeFsPartition> loadPartitions(Collection<Long> ids) {
-    // TODO(todd): implement me
-    return Collections.emptyList();
+    Preconditions.checkState(partitionSpecs_ != null,
+        "Cannot load partitions without having fetched partition IDs " +
+        "from the same LocalFsTable instance");
+    List<String> names = Lists.newArrayList();
+    for (Long id : ids) {
+      LocalPartitionSpec spec = partitionSpecs_.get(id);
+      Preconditions.checkArgument(spec != null, "Invalid partition ID for table %s: %s",
+          getFullName(), id);
+      String name = spec.getName();
+      if (name.isEmpty()) {
+        // Unpartitioned tables don't need to fetch partitions from the metadata
+        // provider. Rather, we just create a partition on the fly.
+        Preconditions.checkState(getNumClusteringCols() == 0,
+            "Cannot fetch empty partition name from a partitioned table");
+        Preconditions.checkArgument(ids.size() == 1,
+            "Expected to only fetch one partition for unpartitioned table %s",
+            getFullName());
+        return Lists.newArrayList(createUnpartitionedPartition(spec));
+      } else {
+        names.add(name);
+      }
+    }
+    Map<String, Partition> partsByName;
+    try {
+      partsByName = db_.getCatalog().getMetaProvider().loadPartitionsByNames(
+          db_.getName(), name_, getClusteringColumnNames(), names);
+    } catch (TException e) {
+      throw new LocalCatalogException(
+          "Could not load partitions for table " + getFullName(), e);
+    }
+    List<FeFsPartition> ret = Lists.newArrayListWithCapacity(ids.size());
+    for (Long id : ids) {
+      LocalPartitionSpec spec = partitionSpecs_.get(id);
+      Partition p = partsByName.get(spec.getName());
+      if (p == null) {
+        // TODO(todd): concurrent drop partition could result in this error.
+        // Should we recover in a more graceful way from such an unexpected event?
+        throw new LocalCatalogException(
+            "Could not load expected partitions for table " + getFullName() +
+            ": missing expected partition with name '" + spec.getName() +
+            "' (perhaps it was concurrently dropped by another process)");
+      }
+      ret.add(new LocalFsPartition(this, spec, p));
+    }
+    return ret;
+  }
+
+  private List<String> getClusteringColumnNames() {
+    List<String> names = Lists.newArrayListWithCapacity(getNumClusteringCols());
+    for (Column c : getClusteringColumns()) {
+      names.add(c.getName());
+    }
+    return names;
+  }
+
+  /**
+   * Create a partition which represents the main partition of an unpartitioned
+   * table.
+   */
+  private LocalFsPartition createUnpartitionedPartition(LocalPartitionSpec spec) {
+    Preconditions.checkArgument(spec.getName().isEmpty());
+    Partition msp = new Partition();
+    msp.setSd(getMetaStoreTable().getSd());
+    msp.setParameters(getMetaStoreTable().getParameters());
+    msp.setValues(Collections.<String>emptyList());
+    return new LocalFsPartition(this, spec, msp);
+  }
+
+  private LocalPartitionSpec createUnpartitionedPartitionSpec() {
+    return new LocalPartitionSpec(this, "", /*id=*/0);
+  }
+
+  private void loadPartitionValueMap() {
+    if (partitionValueMap_ != null) return;
+
+    loadPartitionSpecs();
+    ArrayList<TreeMap<LiteralExpr, HashSet<Long>>> valMapByCol = new ArrayList<>();
+    ArrayList<HashSet<Long>> nullParts = new ArrayList<>();
+
+    for (int i = 0; i < getNumClusteringCols(); i++) {
+      valMapByCol.add(new TreeMap<LiteralExpr, HashSet<Long>>());
+      nullParts.add(new HashSet<Long>());
+    }
+    for (LocalPartitionSpec partition : partitionSpecs_.values()) {
+      List<LiteralExpr> vals = partition.getPartitionValues();
+      for (int i = 0; i < getNumClusteringCols(); i++) {
+        LiteralExpr val = vals.get(i);
+        if (val instanceof NullLiteral) {
+          nullParts.get(i).add(partition.getId());
+          continue;
+        }
+
+        HashSet<Long> ids = valMapByCol.get(i).get(val);
+        if (ids == null) {
+          ids = new HashSet<>();
+          valMapByCol.get(i).put(val,  ids);
+        }
+        ids.add(partition.getId());
+      }
+    }
+    partitionValueMap_ = valMapByCol;
+    nullPartitionIds_ = nullParts;
+  }
+
+  private void loadPartitionSpecs() {
+    if (partitionSpecs_ != null) return;
+
+    if (getNumClusteringCols() == 0) {
+      // Unpartitioned table.
+      // This table has no partition key, which means it has no declared partitions.
+      // We model partitions slightly differently to Hive - every file must exist in a
+      // partition, so add a single partition with no keys which will get all the
+      // files in the table's root directory.
+      partitionSpecs_ = ImmutableMap.of(0L, createUnpartitionedPartitionSpec());
+      return;
+    }
+    List<String> partNames;
+    try {
+      partNames = db_.getCatalog().getMetaProvider().loadPartitionNames(
+          db_.getName(), name_);
+    } catch (TException e) {
+      throw new LocalCatalogException("Could not load partition names for table " +
+          getFullName(), e);
+    }
+    ImmutableMap.Builder<Long, LocalPartitionSpec> b = new ImmutableMap.Builder<>();
+    long id = 0;
+    for (String partName : partNames) {
+      b.put(id, new LocalPartitionSpec(this, partName, id));
+      id++;
+    }
+    partitionSpecs_ = b.build();
   }
 
   @Override
diff --git a/fe/src/main/java/org/apache/impala/catalog/local/LocalPartitionSpec.java b/fe/src/main/java/org/apache/impala/catalog/local/LocalPartitionSpec.java
new file mode 100644
index 0000000..f48f54e
--- /dev/null
+++ b/fe/src/main/java/org/apache/impala/catalog/local/LocalPartitionSpec.java
@@ -0,0 +1,71 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.impala.catalog.local;
+
+import java.util.List;
+
+import javax.annotation.concurrent.Immutable;
+
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.impala.analysis.LiteralExpr;
+import org.apache.impala.catalog.CatalogException;
+import org.apache.impala.catalog.FeCatalogUtils;
+import org.apache.impala.catalog.PrunablePartition;
+import org.apache.impala.util.MetaStoreUtil;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+/**
+ * Specification of a partition of a {@link LocalFsTable} containing
+ * everything necessary for partition pruning.
+ */
+@Immutable
+class LocalPartitionSpec implements PrunablePartition {
+  private final long id_;
+  private final String name_;
+  private final ImmutableList<LiteralExpr> partitionValues_;
+
+  LocalPartitionSpec(LocalFsTable table, String partName, long id) {
+    id_ = id;
+    name_ = Preconditions.checkNotNull(partName);
+    if (!partName.isEmpty()) {
+      try {
+        List<String> partValues = MetaStoreUtil.getPartValsFromName(
+            table.getMetaStoreTable(), partName);
+        partitionValues_ = ImmutableList.copyOf(FeCatalogUtils.parsePartitionKeyValues(
+            table, partValues));
+      } catch (CatalogException | MetaException e) {
+        throw new LocalCatalogException(String.format(
+            "Failed to parse partition name '%s' for table %s",
+            partName, table.getFullName()), e);
+      }
+    } else {
+      // Unpartitioned tables have a single partition with empty name.
+      partitionValues_= ImmutableList.of();
+    }
+  }
+
+  @Override
+  public long getId() { return id_; }
+
+  @Override
+  public List<LiteralExpr> getPartitionValues() { return partitionValues_; }
+
+  String getName() { return name_; }
+}
diff --git a/fe/src/main/java/org/apache/impala/catalog/local/LocalTable.java b/fe/src/main/java/org/apache/impala/catalog/local/LocalTable.java
index 191f248..246b691 100644
--- a/fe/src/main/java/org/apache/impala/catalog/local/LocalTable.java
+++ b/fe/src/main/java/org/apache/impala/catalog/local/LocalTable.java
@@ -56,8 +56,8 @@ import com.google.common.collect.Lists;
 class LocalTable implements FeTable {
   protected final LocalDb db_;
   /** The lower-case name of the table. */
-  private final String name_;
-  private final SchemaInfo schemaInfo_;
+  protected final String name_;
+  protected final SchemaInfo schemaInfo_;
 
   public static LocalTable load(LocalDb db, String tblName) {
     // In order to know which kind of table subclass to instantiate, we need
diff --git a/fe/src/main/java/org/apache/impala/catalog/local/MetaProvider.java b/fe/src/main/java/org/apache/impala/catalog/local/MetaProvider.java
index 6b25257..42bf40e 100644
--- a/fe/src/main/java/org/apache/impala/catalog/local/MetaProvider.java
+++ b/fe/src/main/java/org/apache/impala/catalog/local/MetaProvider.java
@@ -17,9 +17,13 @@
 
 package org.apache.impala.catalog.local;
 
+import java.util.List;
+import java.util.Map;
+
 import org.apache.hadoop.hive.metastore.api.Database;
 import org.apache.hadoop.hive.metastore.api.MetaException;
 import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.Partition;
 import org.apache.hadoop.hive.metastore.api.Table;
 import org.apache.hadoop.hive.metastore.api.UnknownDBException;
 import org.apache.thrift.TException;
@@ -48,4 +52,17 @@ interface MetaProvider {
 
   String loadNullPartitionKeyValue()
       throws MetaException, TException;
+
+  List<String> loadPartitionNames(String dbName, String tableName)
+      throws MetaException, TException;
+
+  /**
+   * Load the given partitions from the specified table.
+   *
+   * If a requested partition does not exist, no exception will be thrown.
+   * Instead, the resulting map will contain no entry for that partition.
+   */
+  Map<String, Partition> loadPartitionsByNames(String dbName, String tableName,
+      List<String> partitionColumnNames, List<String> partitionNames)
+      throws MetaException, TException;
 }
diff --git a/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java b/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
index 23bd142..03258e4 100644
--- a/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
+++ b/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
@@ -23,7 +23,6 @@ import java.util.Collection;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
-import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -45,7 +44,6 @@ import org.apache.hadoop.hive.metastore.api.DecimalColumnStatsData;
 import org.apache.hadoop.hive.metastore.api.DoubleColumnStatsData;
 import org.apache.hadoop.hive.metastore.api.FieldSchema;
 import org.apache.hadoop.hive.metastore.api.LongColumnStatsData;
-import org.apache.hadoop.hive.metastore.api.MetaException;
 import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
 import org.apache.hadoop.hive.metastore.api.Partition;
 import org.apache.hadoop.hive.metastore.api.PrincipalType;
@@ -3338,7 +3336,7 @@ public class CatalogOpExecutor {
 
               partition.setDbName(tblName.getDb());
               partition.setTableName(tblName.getTbl());
-              partition.setValues(getPartValsFromName(msTbl, partName));
+              partition.setValues(MetaStoreUtil.getPartValsFromName(msTbl, partName));
               partition.setParameters(new HashMap<String, String>());
               partition.setSd(msTbl.getSd().deepCopy());
               partition.getSd().setSerdeInfo(msTbl.getSd().getSerdeInfo().deepCopy());
@@ -3438,23 +3436,6 @@ public class CatalogOpExecutor {
     return response;
   }
 
-  private List<String> getPartValsFromName(org.apache.hadoop.hive.metastore.api.Table
-      msTbl, String partName) throws MetaException, CatalogException {
-    Preconditions.checkNotNull(msTbl);
-    LinkedHashMap<String, String> hm =
-        org.apache.hadoop.hive.metastore.Warehouse.makeSpecFromName(partName);
-    List<String> partVals = Lists.newArrayList();
-    for (FieldSchema field: msTbl.getPartitionKeys()) {
-      String key = field.getName();
-      String val = hm.get(key);
-      if (val == null) {
-        throw new CatalogException("Incomplete partition name - missing " + key);
-      }
-      partVals.add(val);
-    }
-    return partVals;
-  }
-
   /**
    * Returns an existing, loaded table from the Catalog. Throws an exception if any
    * of the following are true:
diff --git a/fe/src/main/java/org/apache/impala/util/MetaStoreUtil.java b/fe/src/main/java/org/apache/impala/util/MetaStoreUtil.java
index 5a5654a..bffd46a 100644
--- a/fe/src/main/java/org/apache/impala/util/MetaStoreUtil.java
+++ b/fe/src/main/java/org/apache/impala/util/MetaStoreUtil.java
@@ -18,14 +18,19 @@
 package org.apache.impala.util;
 
 import java.util.HashSet;
+import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 
 import org.apache.hadoop.hive.conf.HiveConf;
 import org.apache.hadoop.hive.metastore.IMetaStoreClient;
+import org.apache.hadoop.hive.metastore.Warehouse;
 import org.apache.hadoop.hive.metastore.api.ConfigValSecurityException;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
 import org.apache.hadoop.hive.metastore.api.MetaException;
 import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.impala.catalog.CatalogException;
 import org.apache.impala.catalog.HdfsTable;
 import org.apache.impala.common.AnalysisException;
 import org.apache.impala.compat.MetastoreShim;
@@ -260,4 +265,20 @@ public class MetaStoreUtil {
     }
     return Joiner.on(",").join(outputList);
   }
+
+  public static List<String> getPartValsFromName(Table msTbl, String partName)
+      throws MetaException, CatalogException {
+    Preconditions.checkNotNull(msTbl);
+    LinkedHashMap<String, String> hm = Warehouse.makeSpecFromName(partName);
+    List<String> partVals = Lists.newArrayList();
+    for (FieldSchema field: msTbl.getPartitionKeys()) {
+      String key = field.getName();
+      String val = hm.get(key);
+      if (val == null) {
+        throw new CatalogException("Incomplete partition name - missing " + key);
+      }
+      partVals.add(val);
+    }
+    return partVals;
+  }
 }
diff --git a/fe/src/test/java/org/apache/impala/catalog/CatalogTest.java b/fe/src/test/java/org/apache/impala/catalog/CatalogTest.java
index eeceb36..856fc95 100644
--- a/fe/src/test/java/org/apache/impala/catalog/CatalogTest.java
+++ b/fe/src/test/java/org/apache/impala/catalog/CatalogTest.java
@@ -287,6 +287,13 @@ public class CatalogTest {
   public void TestPartitions() throws CatalogException {
     HdfsTable table =
         (HdfsTable) catalog_.getOrLoadTable("functional", "AllTypes");
+    checkAllTypesPartitioning(table, true);
+  }
+
+  public static void checkAllTypesPartitioning(FeFsTable table,
+      boolean checkFileDescriptors) {
+    assertEquals(24, table.getPartitionIds().size());
+    assertEquals(24, table.getPartitions().size());
     Collection<? extends FeFsPartition> partitions =
         FeCatalogUtils.loadAllPartitions(table);
 
@@ -309,7 +316,11 @@ public class CatalogTest {
 
       months.add(key1 * 100 + key2);
 
-      assertEquals(p.getFileDescriptors().size(), 1);
+      if (checkFileDescriptors) {
+        // TODO(todd): once LocalCatalog supports file descriptors,
+        // no need for this boolean anymore.
+        assertEquals(p.getFileDescriptors().size(), 1);
+      }
     }
     assertEquals(months.size(), 24);
   }
diff --git a/fe/src/test/java/org/apache/impala/catalog/local/LocalCatalogTest.java b/fe/src/test/java/org/apache/impala/catalog/local/LocalCatalogTest.java
index a296399..aabb873 100644
--- a/fe/src/test/java/org/apache/impala/catalog/local/LocalCatalogTest.java
+++ b/fe/src/test/java/org/apache/impala/catalog/local/LocalCatalogTest.java
@@ -22,7 +22,9 @@ import static org.junit.Assert.*;
 import java.util.Set;
 
 import org.apache.impala.catalog.CatalogTest;
+import org.apache.impala.catalog.FeCatalogUtils;
 import org.apache.impala.catalog.FeDb;
+import org.apache.impala.catalog.FeFsPartition;
 import org.apache.impala.catalog.FeFsTable;
 import org.apache.impala.catalog.FeTable;
 import org.apache.impala.catalog.Type;
@@ -33,6 +35,7 @@ import org.junit.Before;
 import org.junit.Test;
 
 import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
 
 public class LocalCatalogTest {
 
@@ -99,7 +102,33 @@ public class LocalCatalogTest {
     FeFsTable fsTable = (FeFsTable) t;
     assertEquals(MetaStoreUtil.DEFAULT_NULL_PARTITION_KEY_VALUE,
         fsTable.getNullPartitionKeyValue());
+
+    // Stats should have one row per partition, plus a "total" row.
     TResultSet stats = fsTable.getTableStats();
-    assertEquals(1, stats.getRowsSize());
+    assertEquals(25, stats.getRowsSize());
+  }
+
+  @Test
+  public void testPartitioning() throws Exception {
+    FeFsTable t = (FeFsTable) catalog_.getTable("functional",  "alltypes");
+    // TODO(todd): once we support file descriptors in LocalCatalog,
+    // run the full test.
+    CatalogTest.checkAllTypesPartitioning(t, /*checkFileDescriptors=*/false);
+  }
+
+  /**
+   * Test that partitions with a NULL value can be properly loaded.
+   */
+  @Test
+  public void testEmptyPartitionValue() throws Exception {
+    FeFsTable t = (FeFsTable) catalog_.getTable("functional",  "alltypesagg");
+    // This table has one partition with a NULL value for the 'day'
+    // clustering column.
+    int dayCol = t.getColumn("day").getPosition();
+    Set<Long> ids = t.getNullPartitionIds(dayCol);
+    assertEquals(1,  ids.size());
+    FeFsPartition partition = FeCatalogUtils.loadPartition(
+        t, Iterables.getOnlyElement(ids));
+    assertTrue(partition.getPartitionValue(dayCol).isNullLiteral());
   }
 }


[impala] 05/13: IMPALA-5202: Disallow PREPARE:WAIT debug action

Posted by ta...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tarmstrong pushed a commit to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git

commit 98e0126e95c7901665eec36dbbf5e1e5b3a6ee42
Author: Dan Hecht <dh...@cloudera.com>
AuthorDate: Wed Jun 20 14:49:57 2018 -0700

    IMPALA-5202: Disallow PREPARE:WAIT debug action
    
    In order to simplify FIS startup, we don't allow cancellation until all
    FIS have finished Prepare(), so we shouldn't allow PREPARE:WAIT since
    there will be no way to cancel out of the loop.  Make this explicit.
    
    Change-Id: I1caa4f8e6ce7f32a8a3722648e08e24f34dba35d
    Reviewed-on: http://gerrit.cloudera.org:8080/10776
    Reviewed-by: Dan Hecht <dh...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
 be/src/exec/exec-node.cc         |  2 ++
 be/src/runtime/debug-options.cc  | 11 ++++++++---
 tests/failure/test_failpoints.py |  8 +++++---
 3 files changed, 15 insertions(+), 6 deletions(-)

diff --git a/be/src/exec/exec-node.cc b/be/src/exec/exec-node.cc
index 504a419..7cdd054 100644
--- a/be/src/exec/exec-node.cc
+++ b/be/src/exec/exec-node.cc
@@ -408,6 +408,8 @@ Status ExecNode::ExecDebugActionImpl(TExecNodePhase::type phase, RuntimeState* s
   if (debug_options_.action == TDebugAction::FAIL) {
     return Status(TErrorCode::INTERNAL_ERROR, "Debug Action: FAIL");
   } else if (debug_options_.action == TDebugAction::WAIT) {
+    // See DebugOptions::DebugOptions().
+    DCHECK(phase != TExecNodePhase::PREPARE && phase != TExecNodePhase::CLOSE);
     while (!state->is_cancelled()) {
       sleep(1);
     }
diff --git a/be/src/runtime/debug-options.cc b/be/src/runtime/debug-options.cc
index 6e5062d..b8b6b35 100644
--- a/be/src/runtime/debug-options.cc
+++ b/be/src/runtime/debug-options.cc
@@ -65,9 +65,14 @@ DebugOptions::DebugOptions(const TQueryOptions& query_options)
       phase_ = TExecNodePhase::INVALID;
       return;
     }
-    if (phase_ == TExecNodePhase::CLOSE && action_ == TDebugAction::WAIT) {
-      LOG(WARNING) << "Do not use CLOSE:WAIT debug actions because nodes cannot be "
-          "cancelled in Close()";
+    if ((phase_ == TExecNodePhase::PREPARE || phase_ == TExecNodePhase::CLOSE) &&
+        action_ == TDebugAction::WAIT) {
+      // Cancellation is not allowed before PREPARE phase completes (to keep FIS
+      // startup simpler - it will be checked immediately after when execution begins).
+      // Close() must always run to completion to free resources, so cancellation does
+      // not make sense for the CLOSE phase and is not checked. So we disallow these.
+      LOG(WARNING) << Substitute("Do not use $0:$1 debug actions because nodes cannot "
+          "be cancelled in that phase.", *phase_str, *action_str);
       phase_ = TExecNodePhase::INVALID;
       return;
     }
diff --git a/tests/failure/test_failpoints.py b/tests/failure/test_failpoints.py
index 9f54257..7366900 100644
--- a/tests/failure/test_failpoints.py
+++ b/tests/failure/test_failpoints.py
@@ -75,6 +75,11 @@ class TestFailpoints(ImpalaTestSuite):
     cls.ImpalaTestMatrix.add_dimension(
         create_exec_option_dimension([0], [False], [0]))
 
+    # Don't create PREPARE:WAIT debug actions because cancellation is not checked until
+    # after the prepare phase once execution is started.
+    cls.ImpalaTestMatrix.add_constraint(
+        lambda v: not (v.get_value('action') == 'CANCEL'
+                     and v.get_value('location') == 'PREPARE'))
     # Don't create CLOSE:WAIT debug actions to avoid leaking plan fragments (there's no
     # way to cancel a plan fragment once Close() has been called)
     cls.ImpalaTestMatrix.add_constraint(
@@ -90,9 +95,6 @@ class TestFailpoints(ImpalaTestSuite):
     location = vector.get_value('location')
     vector.get_value('exec_option')['mt_dop'] = vector.get_value('mt_dop')
 
-    if action == "CANCEL" and location == "PREPARE":
-      pytest.xfail(reason="IMPALA-5202 leads to a hang.")
-
     try:
       plan_node_ids = self.__parse_plan_nodes_from_explain(query, vector)
     except ImpalaBeeswaxException as e: