use of org.apache.drill.exec.work.foreman.ForemanSetupException in project drill by apache.
the class SplittingParallelizer method generateWorkUnits.
/**
* Split plan into multiple plans based on parallelization
* Ideally it is applicable only to plans with two major fragments: Screen and UnionExchange
* But there could be cases where we can remove even multiple exchanges like in case of "order by"
* End goal is to get single major fragment: Screen with chain that ends up with a single minor fragment
* from Leaf Exchange. This way each plan can run independently without any exchange involvement
* @param options
* @param foremanNode - not really applicable
* @param queryId
* @param reader
* @param rootNode
* @param planningSet
* @param session
* @param queryContextInfo
* @return
* @throws ExecutionSetupException
*/
private List<QueryWorkUnit> generateWorkUnits(OptionList options, DrillbitEndpoint foremanNode, QueryId queryId, PhysicalPlanReader reader, Fragment rootNode, PlanningSet planningSet, UserSession session, QueryContextInformation queryContextInfo) throws ExecutionSetupException {
// now we generate all the individual plan fragments and associated assignments. Note, we need all endpoints
// assigned before we can materialize, so we start a new loop here rather than utilizing the previous one.
List<QueryWorkUnit> workUnits = Lists.newArrayList();
int plansCount = 0;
DrillbitEndpoint[] endPoints = null;
long initialAllocation = 0;
long maxAllocation = 0;
final Iterator<Wrapper> iter = planningSet.iterator();
while (iter.hasNext()) {
Wrapper wrapper = iter.next();
Fragment node = wrapper.getNode();
boolean isLeafFragment = node.getReceivingExchangePairs().size() == 0;
final PhysicalOperator physicalOperatorRoot = node.getRoot();
// get all the needed info from leaf fragment
if ((physicalOperatorRoot instanceof Exchange) && isLeafFragment) {
// need to get info about
// number of minor fragments
// assignedEndPoints
// allocation
plansCount = wrapper.getWidth();
initialAllocation = (wrapper.getInitialAllocation() != 0) ? wrapper.getInitialAllocation() / plansCount : 0;
maxAllocation = (wrapper.getMaxAllocation() != 0) ? wrapper.getMaxAllocation() / plansCount : 0;
endPoints = new DrillbitEndpoint[plansCount];
for (int mfId = 0; mfId < plansCount; mfId++) {
endPoints[mfId] = wrapper.getAssignedEndpoint(mfId);
}
}
}
if (plansCount == 0) {
// no exchange, return list of single QueryWorkUnit
workUnits.add(generateWorkUnit(options, foremanNode, queryId, reader, rootNode, planningSet, session, queryContextInfo));
return workUnits;
}
for (Wrapper wrapper : planningSet) {
Fragment node = wrapper.getNode();
final PhysicalOperator physicalOperatorRoot = node.getRoot();
if (physicalOperatorRoot instanceof Exchange) {
// get to 0 MajorFragment
continue;
}
boolean isRootNode = rootNode == node;
if (isRootNode && wrapper.getWidth() != 1) {
throw new ForemanSetupException(String.format("Failure while trying to setup fragment. " + "The root fragment must always have parallelization one. In the current case, the width was set to %d.", wrapper.getWidth()));
}
// this fragment is always leaf, as we are removing all the exchanges
boolean isLeafFragment = true;
FragmentHandle handle = //
FragmentHandle.newBuilder().setMajorFragmentId(//
wrapper.getMajorFragmentId()).setMinorFragmentId(// minor fragment ID is going to be always 0, as plan will be split
0).setQueryId(//
queryId).build();
// Create a minorFragment for each major fragment.
for (int minorFragmentId = 0; minorFragmentId < plansCount; minorFragmentId++) {
// those fragments should be empty
List<PlanFragment> fragments = Lists.newArrayList();
PlanFragment rootFragment = null;
FragmentRoot rootOperator = null;
IndexedFragmentNode iNode = new IndexedFragmentNode(minorFragmentId, wrapper);
wrapper.resetAllocation();
// two visitors here
// 1. To remove exchange
// 2. To reset operator IDs as exchanges were removed
PhysicalOperator op = physicalOperatorRoot.accept(ExchangeRemoverMaterializer.INSTANCE, iNode).accept(OperatorIdVisitor.INSTANCE, 0);
Preconditions.checkArgument(op instanceof FragmentRoot);
FragmentRoot root = (FragmentRoot) op;
// get plan as JSON
String plan;
String optionsData;
try {
plan = reader.writeJson(root);
optionsData = reader.writeJson(options);
} catch (JsonProcessingException e) {
throw new ForemanSetupException("Failure while trying to convert fragment into json.", e);
}
PlanFragment fragment = //
PlanFragment.newBuilder().setForeman(//
endPoints[minorFragmentId]).setFragmentJson(//
plan).setHandle(//
handle).setAssignment(//
endPoints[minorFragmentId]).setLeafFragment(//
isLeafFragment).setContext(queryContextInfo).setMemInitial(//
initialAllocation).setMemMax(// TODO - for some reason OOM is using leaf fragment max allocation divided by width
wrapper.getMaxAllocation()).setOptionsJson(optionsData).setCredentials(session.getCredentials()).addAllCollector(CountRequiredFragments.getCollectors(root)).build();
if (isRootNode) {
if (logger.isDebugEnabled()) {
logger.debug("Root fragment:\n {}", DrillStringUtils.unescapeJava(fragment.toString()));
}
rootFragment = fragment;
rootOperator = root;
} else {
if (logger.isDebugEnabled()) {
logger.debug("Remote fragment:\n {}", DrillStringUtils.unescapeJava(fragment.toString()));
}
throw new ForemanSetupException(String.format("There should not be non-root/remote fragment present in plan split, but there is:", DrillStringUtils.unescapeJava(fragment.toString())));
}
// fragments should be always empty here
workUnits.add(new QueryWorkUnit(rootOperator, rootFragment, fragments));
}
}
return workUnits;
}
use of org.apache.drill.exec.work.foreman.ForemanSetupException in project drill by apache.
the class DescribeTableHandler method rewrite.
/** Rewrite the parse tree as SELECT ... FROM INFORMATION_SCHEMA.COLUMNS ... */
@Override
public SqlNode rewrite(SqlNode sqlNode) throws RelConversionException, ForemanSetupException {
SqlDescribeTable node = unwrap(sqlNode, SqlDescribeTable.class);
try {
List<SqlNode> selectList = ImmutableList.of((SqlNode) new SqlIdentifier(COLS_COL_COLUMN_NAME, SqlParserPos.ZERO), new SqlIdentifier(COLS_COL_DATA_TYPE, SqlParserPos.ZERO), new SqlIdentifier(COLS_COL_IS_NULLABLE, SqlParserPos.ZERO));
SqlNode fromClause = new SqlIdentifier(ImmutableList.of(IS_SCHEMA_NAME, TAB_COLUMNS), null, SqlParserPos.ZERO, null);
final SqlIdentifier table = node.getTable();
final SchemaPlus defaultSchema = config.getConverter().getDefaultSchema();
final List<String> schemaPathGivenInCmd = Util.skipLast(table.names);
final SchemaPlus schema = SchemaUtilites.findSchema(defaultSchema, schemaPathGivenInCmd);
final String charset = Util.getDefaultCharset().name();
if (schema == null) {
SchemaUtilites.throwSchemaNotFoundException(defaultSchema, SchemaUtilites.SCHEMA_PATH_JOINER.join(schemaPathGivenInCmd));
}
if (SchemaUtilites.isRootSchema(schema)) {
throw UserException.validationError().message("No schema selected.").build(logger);
}
final String tableName = Util.last(table.names);
// find resolved schema path
final String schemaPath = SchemaUtilites.unwrapAsDrillSchemaInstance(schema).getFullSchemaName();
if (schema.getTable(tableName) == null) {
throw UserException.validationError().message("Unknown table [%s] in schema [%s]", tableName, schemaPath).build(logger);
}
SqlNode schemaCondition = null;
if (!SchemaUtilites.isRootSchema(schema)) {
schemaCondition = DrillParserUtil.createCondition(new SqlIdentifier(SHRD_COL_TABLE_SCHEMA, SqlParserPos.ZERO), SqlStdOperatorTable.EQUALS, SqlLiteral.createCharString(schemaPath, charset, SqlParserPos.ZERO));
}
SqlNode where = DrillParserUtil.createCondition(new SqlIdentifier(SHRD_COL_TABLE_NAME, SqlParserPos.ZERO), SqlStdOperatorTable.EQUALS, SqlLiteral.createCharString(tableName, charset, SqlParserPos.ZERO));
where = DrillParserUtil.createCondition(schemaCondition, SqlStdOperatorTable.AND, where);
SqlNode columnFilter = null;
if (node.getColumn() != null) {
columnFilter = DrillParserUtil.createCondition(new SqlIdentifier(COLS_COL_COLUMN_NAME, SqlParserPos.ZERO), SqlStdOperatorTable.EQUALS, SqlLiteral.createCharString(node.getColumn().toString(), charset, SqlParserPos.ZERO));
} else if (node.getColumnQualifier() != null) {
columnFilter = DrillParserUtil.createCondition(new SqlIdentifier(COLS_COL_COLUMN_NAME, SqlParserPos.ZERO), SqlStdOperatorTable.LIKE, node.getColumnQualifier());
}
where = DrillParserUtil.createCondition(where, SqlStdOperatorTable.AND, columnFilter);
return new SqlSelect(SqlParserPos.ZERO, null, new SqlNodeList(selectList, SqlParserPos.ZERO), fromClause, where, null, null, null, null, null, null);
} catch (Exception ex) {
throw UserException.planError(ex).message("Error while rewriting DESCRIBE query: %d", ex.getMessage()).build(logger);
}
}
use of org.apache.drill.exec.work.foreman.ForemanSetupException in project drill by apache.
the class SimpleParallelizer method generateWorkUnit.
protected QueryWorkUnit generateWorkUnit(OptionList options, DrillbitEndpoint foremanNode, QueryId queryId, PhysicalPlanReader reader, Fragment rootNode, PlanningSet planningSet, UserSession session, QueryContextInformation queryContextInfo) throws ExecutionSetupException {
List<PlanFragment> fragments = Lists.newArrayList();
PlanFragment rootFragment = null;
FragmentRoot rootOperator = null;
// assigned before we can materialize, so we start a new loop here rather than utilizing the previous one.
for (Wrapper wrapper : planningSet) {
Fragment node = wrapper.getNode();
final PhysicalOperator physicalOperatorRoot = node.getRoot();
boolean isRootNode = rootNode == node;
if (isRootNode && wrapper.getWidth() != 1) {
throw new ForemanSetupException(String.format("Failure while trying to setup fragment. " + "The root fragment must always have parallelization one. In the current case, the width was set to %d.", wrapper.getWidth()));
}
// a fragment is self driven if it doesn't rely on any other exchanges.
boolean isLeafFragment = node.getReceivingExchangePairs().size() == 0;
// Create a minorFragment for each major fragment.
for (int minorFragmentId = 0; minorFragmentId < wrapper.getWidth(); minorFragmentId++) {
IndexedFragmentNode iNode = new IndexedFragmentNode(minorFragmentId, wrapper);
wrapper.resetAllocation();
PhysicalOperator op = physicalOperatorRoot.accept(Materializer.INSTANCE, iNode);
Preconditions.checkArgument(op instanceof FragmentRoot);
FragmentRoot root = (FragmentRoot) op;
// get plan as JSON
String plan;
String optionsData;
try {
plan = reader.writeJson(root);
optionsData = reader.writeJson(options);
} catch (JsonProcessingException e) {
throw new ForemanSetupException("Failure while trying to convert fragment into json.", e);
}
FragmentHandle handle = //
FragmentHandle.newBuilder().setMajorFragmentId(//
wrapper.getMajorFragmentId()).setMinorFragmentId(//
minorFragmentId).setQueryId(//
queryId).build();
PlanFragment fragment = //
PlanFragment.newBuilder().setForeman(//
foremanNode).setFragmentJson(//
plan).setHandle(//
handle).setAssignment(//
wrapper.getAssignedEndpoint(minorFragmentId)).setLeafFragment(//
isLeafFragment).setContext(queryContextInfo).setMemInitial(//
wrapper.getInitialAllocation()).setMemMax(wrapper.getMaxAllocation()).setOptionsJson(optionsData).setCredentials(session.getCredentials()).addAllCollector(CountRequiredFragments.getCollectors(root)).build();
if (isRootNode) {
if (logger.isDebugEnabled()) {
logger.debug("Root fragment:\n {}", DrillStringUtils.unescapeJava(fragment.toString()));
}
rootFragment = fragment;
rootOperator = root;
} else {
if (logger.isDebugEnabled()) {
logger.debug("Remote fragment:\n {}", DrillStringUtils.unescapeJava(fragment.toString()));
}
fragments.add(fragment);
}
}
}
return new QueryWorkUnit(rootOperator, rootFragment, fragments);
}
use of org.apache.drill.exec.work.foreman.ForemanSetupException in project drill by apache.
the class RefreshMetadataHandler method getPlan.
@Override
public PhysicalPlan getPlan(SqlNode sqlNode) throws ValidationException, RelConversionException, IOException, ForemanSetupException {
final SqlRefreshMetadata refreshTable = unwrap(sqlNode, SqlRefreshMetadata.class);
try {
final SchemaPlus schema = findSchema(config.getConverter().getDefaultSchema(), refreshTable.getSchemaPath());
if (schema == null) {
return direct(false, "Storage plugin or workspace does not exist [%s]", SchemaUtilites.SCHEMA_PATH_JOINER.join(refreshTable.getSchemaPath()));
}
final String tableName = refreshTable.getName();
if (tableName.contains("*") || tableName.contains("?")) {
return direct(false, "Glob path %s not supported for metadata refresh", tableName);
}
final Table table = schema.getTable(tableName);
if (table == null) {
return direct(false, "Table %s does not exist.", tableName);
}
if (!(table instanceof DrillTable)) {
return notSupported(tableName);
}
final DrillTable drillTable = (DrillTable) table;
final Object selection = drillTable.getSelection();
if (!(selection instanceof FormatSelection)) {
return notSupported(tableName);
}
FormatSelection formatSelection = (FormatSelection) selection;
FormatPluginConfig formatConfig = formatSelection.getFormat();
if (!((formatConfig instanceof ParquetFormatConfig) || ((formatConfig instanceof NamedFormatPluginConfig) && ((NamedFormatPluginConfig) formatConfig).name.equals("parquet")))) {
return notSupported(tableName);
}
FileSystemPlugin plugin = (FileSystemPlugin) drillTable.getPlugin();
DrillFileSystem fs = new DrillFileSystem(plugin.getFormatPlugin(formatSelection.getFormat()).getFsConf());
String selectionRoot = formatSelection.getSelection().selectionRoot;
if (!fs.getFileStatus(new Path(selectionRoot)).isDirectory()) {
return notSupported(tableName);
}
if (!(formatConfig instanceof ParquetFormatConfig)) {
formatConfig = new ParquetFormatConfig();
}
Metadata.createMeta(fs, selectionRoot, (ParquetFormatConfig) formatConfig);
return direct(true, "Successfully updated metadata for table %s.", tableName);
} catch (Exception e) {
logger.error("Failed to update metadata for table '{}'", refreshTable.getName(), e);
return DirectPlan.createDirectPlan(context, false, String.format("Error: %s", e.getMessage()));
}
}
use of org.apache.drill.exec.work.foreman.ForemanSetupException in project drill by apache.
the class DropFunctionHandler method getPlan.
/**
* Unregisters UDFs dynamically. Process consists of several steps:
* <ol>
* <li>Registering jar in jar registry to ensure that several jars with the same name is not being unregistered.</li>
* <li>Starts remote unregistration process, gets list of all jars and excludes jar to be deleted.</li>
* <li>Signals drill bits to start local unregistration process.</li>
* <li>Removes source and binary jars from registry area.</li>
* </ol>
*
* UDFs unregistration is allowed only if dynamic UDFs support is enabled.
* Only jars registered dynamically can be unregistered,
* built-in functions loaded at start up are not allowed to be unregistered.
*
* Limitation: before jar unregistration make sure no one is using functions from this jar.
* There is no guarantee that running queries will finish successfully or give correct result.
*
* @return - Single row indicating list of unregistered UDFs, raise exception otherwise
*/
@Override
public PhysicalPlan getPlan(SqlNode sqlNode) throws ForemanSetupException, IOException {
if (!context.getOption(ExecConstants.DYNAMIC_UDF_SUPPORT_ENABLED).bool_val) {
throw UserException.validationError().message("Dynamic UDFs support is disabled.").build(logger);
}
SqlDropFunction node = unwrap(sqlNode, SqlDropFunction.class);
String jarName = ((SqlCharStringLiteral) node.getJar()).toValue();
RemoteFunctionRegistry remoteFunctionRegistry = context.getRemoteFunctionRegistry();
boolean inProgress = false;
try {
final String action = remoteFunctionRegistry.addToJars(jarName, RemoteFunctionRegistry.Action.UNREGISTRATION);
if (!(inProgress = action == null)) {
return DirectPlan.createDirectPlan(context, false, String.format("Jar with %s name is used. Action: %s", jarName, action));
}
Jar deletedJar = unregister(jarName, remoteFunctionRegistry);
if (deletedJar == null) {
return DirectPlan.createDirectPlan(context, false, String.format("Jar %s is not registered in remote registry", jarName));
}
remoteFunctionRegistry.submitForUnregistration(jarName);
removeJarFromArea(jarName, remoteFunctionRegistry.getFs(), remoteFunctionRegistry.getRegistryArea());
removeJarFromArea(JarUtil.getSourceName(jarName), remoteFunctionRegistry.getFs(), remoteFunctionRegistry.getRegistryArea());
return DirectPlan.createDirectPlan(context, true, String.format("The following UDFs in jar %s have been unregistered:\n%s", jarName, deletedJar.getFunctionSignatureList()));
} catch (Exception e) {
logger.error("Error during UDF unregistration", e);
return DirectPlan.createDirectPlan(context, false, e.getMessage());
} finally {
if (inProgress) {
remoteFunctionRegistry.finishUnregistration(jarName);
remoteFunctionRegistry.removeFromJars(jarName);
}
}
}
Aggregations