Search in sources :

Example 1 with LockException

use of org.apache.hadoop.hive.ql.lockmgr.LockException in project hive by apache.

the class Driver method compile.

// deferClose indicates if the close/destroy should be deferred when the process has been
// interrupted, it should be set to true if the compile is called within another method like
// runInternal, which defers the close to the called in that method.
private void compile(String command, boolean resetTaskIds, boolean deferClose) throws CommandProcessorResponse {
    PerfLogger perfLogger = SessionState.getPerfLogger(true);
    perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.DRIVER_RUN);
    perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.COMPILE);
    lDrvState.stateLock.lock();
    try {
        lDrvState.driverState = DriverState.COMPILING;
    } finally {
        lDrvState.stateLock.unlock();
    }
    command = new VariableSubstitution(new HiveVariableSource() {

        @Override
        public Map<String, String> getHiveVariable() {
            return SessionState.get().getHiveVariables();
        }
    }).substitute(conf, command);
    String queryStr = command;
    try {
        // command should be redacted to avoid to logging sensitive data
        queryStr = HookUtils.redactLogString(conf, command);
    } catch (Exception e) {
        LOG.warn("WARNING! Query command could not be redacted." + e);
    }
    checkInterrupted("at beginning of compilation.", null, null);
    if (ctx != null && ctx.getExplainAnalyze() != AnalyzeState.RUNNING) {
        // close the existing ctx etc before compiling a new query, but does not destroy driver
        closeInProcess(false);
    }
    if (resetTaskIds) {
        TaskFactory.resetId();
    }
    LockedDriverState.setLockedDriverState(lDrvState);
    String queryId = queryState.getQueryId();
    if (ctx != null) {
        setTriggerContext(queryId);
    }
    // save some info for webUI for use after plan is freed
    this.queryDisplay.setQueryStr(queryStr);
    this.queryDisplay.setQueryId(queryId);
    LOG.info("Compiling command(queryId=" + queryId + "): " + queryStr);
    conf.setQueryString(queryStr);
    // FIXME: sideeffect will leave the last query set at the session level
    SessionState.get().getConf().setQueryString(queryStr);
    SessionState.get().setupQueryCurrentTimestamp();
    // Whether any error occurred during query compilation. Used for query lifetime hook.
    boolean compileError = false;
    boolean parseError = false;
    try {
        // Initialize the transaction manager.  This must be done before analyze is called.
        if (initTxnMgr != null) {
            queryTxnMgr = initTxnMgr;
        } else {
            queryTxnMgr = SessionState.get().initTxnMgr(conf);
        }
        if (queryTxnMgr instanceof Configurable) {
            ((Configurable) queryTxnMgr).setConf(conf);
        }
        queryState.setTxnManager(queryTxnMgr);
        // In case when user Ctrl-C twice to kill Hive CLI JVM, we want to release locks
        // if compile is being called multiple times, clear the old shutdownhook
        ShutdownHookManager.removeShutdownHook(shutdownRunner);
        final HiveTxnManager txnMgr = queryTxnMgr;
        shutdownRunner = new Runnable() {

            @Override
            public void run() {
                try {
                    releaseLocksAndCommitOrRollback(false, txnMgr);
                } catch (LockException e) {
                    LOG.warn("Exception when releasing locks in ShutdownHook for Driver: " + e.getMessage());
                }
            }
        };
        ShutdownHookManager.addShutdownHook(shutdownRunner, SHUTDOWN_HOOK_PRIORITY);
        checkInterrupted("before parsing and analysing the query", null, null);
        if (ctx == null) {
            ctx = new Context(conf);
            setTriggerContext(queryId);
        }
        ctx.setRuntimeStatsSource(runtimeStatsSource);
        ctx.setCmd(command);
        ctx.setHDFSCleanup(true);
        perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.PARSE);
        // Trigger query hook before compilation
        hookRunner.runBeforeParseHook(command);
        ASTNode tree;
        try {
            tree = ParseUtils.parse(command, ctx);
        } catch (ParseException e) {
            parseError = true;
            throw e;
        } finally {
            hookRunner.runAfterParseHook(command, parseError);
        }
        perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.PARSE);
        hookRunner.runBeforeCompileHook(command);
        perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.ANALYZE);
        // Flush the metastore cache.  This assures that we don't pick up objects from a previous
        // query running in this same thread.  This has to be done after we get our semantic
        // analyzer (this is when the connection to the metastore is made) but before we analyze,
        // because at that point we need access to the objects.
        Hive.get().getMSC().flushCache();
        BaseSemanticAnalyzer sem;
        // Do semantic analysis and plan generation
        if (hookRunner.hasPreAnalyzeHooks()) {
            HiveSemanticAnalyzerHookContext hookCtx = new HiveSemanticAnalyzerHookContextImpl();
            hookCtx.setConf(conf);
            hookCtx.setUserName(userName);
            hookCtx.setIpAddress(SessionState.get().getUserIpAddress());
            hookCtx.setCommand(command);
            hookCtx.setHiveOperation(queryState.getHiveOperation());
            tree = hookRunner.runPreAnalyzeHooks(hookCtx, tree);
            sem = SemanticAnalyzerFactory.get(queryState, tree);
            openTransaction();
            sem.analyze(tree, ctx);
            hookCtx.update(sem);
            hookRunner.runPostAnalyzeHooks(hookCtx, sem.getAllRootTasks());
        } else {
            sem = SemanticAnalyzerFactory.get(queryState, tree);
            openTransaction();
            sem.analyze(tree, ctx);
        }
        LOG.info("Semantic Analysis Completed");
        // Retrieve information about cache usage for the query.
        if (conf.getBoolVar(HiveConf.ConfVars.HIVE_QUERY_RESULTS_CACHE_ENABLED)) {
            cacheUsage = sem.getCacheUsage();
        }
        // validate the plan
        sem.validate();
        perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.ANALYZE);
        checkInterrupted("after analyzing query.", null, null);
        // get the output schema
        schema = getSchema(sem, conf);
        plan = new QueryPlan(queryStr, sem, perfLogger.getStartTime(PerfLogger.DRIVER_RUN), queryId, queryState.getHiveOperation(), schema);
        conf.set("mapreduce.workflow.id", "hive_" + queryId);
        conf.set("mapreduce.workflow.name", queryStr);
        // initialize FetchTask right here
        if (plan.getFetchTask() != null) {
            plan.getFetchTask().initialize(queryState, plan, null, ctx.getOpContext());
        }
        // do the authorization check
        if (!sem.skipAuthorization() && HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVE_AUTHORIZATION_ENABLED)) {
            try {
                perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.DO_AUTHORIZATION);
                doAuthorization(queryState.getHiveOperation(), sem, command);
            } catch (AuthorizationException authExp) {
                console.printError("Authorization failed:" + authExp.getMessage() + ". Use SHOW GRANT to get more details.");
                errorMessage = authExp.getMessage();
                SQLState = "42000";
                throw createProcessorResponse(403);
            } finally {
                perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.DO_AUTHORIZATION);
            }
        }
        if (conf.getBoolVar(ConfVars.HIVE_LOG_EXPLAIN_OUTPUT)) {
            String explainOutput = getExplainOutput(sem, plan, tree);
            if (explainOutput != null) {
                LOG.info("EXPLAIN output for queryid " + queryId + " : " + explainOutput);
                if (conf.isWebUiQueryInfoCacheEnabled()) {
                    queryDisplay.setExplainPlan(explainOutput);
                }
            }
        }
    } catch (CommandProcessorResponse cpr) {
        throw cpr;
    } catch (Exception e) {
        checkInterrupted("during query compilation: " + e.getMessage(), null, null);
        compileError = true;
        ErrorMsg error = ErrorMsg.getErrorMsg(e.getMessage());
        errorMessage = "FAILED: " + e.getClass().getSimpleName();
        if (error != ErrorMsg.GENERIC_ERROR) {
            errorMessage += " [Error " + error.getErrorCode() + "]:";
        }
        // HIVE-4889
        if ((e instanceof IllegalArgumentException) && e.getMessage() == null && e.getCause() != null) {
            errorMessage += " " + e.getCause().getMessage();
        } else {
            errorMessage += " " + e.getMessage();
        }
        if (error == ErrorMsg.TXNMGR_NOT_ACID) {
            errorMessage += ". Failed command: " + queryStr;
        }
        SQLState = error.getSQLState();
        downstreamError = e;
        console.printError(errorMessage, "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e));
        throw createProcessorResponse(error.getErrorCode());
    } finally {
        // before/after execution hook will never be executed.
        if (!parseError) {
            try {
                hookRunner.runAfterCompilationHook(command, compileError);
            } catch (Exception e) {
                LOG.warn("Failed when invoking query after-compilation hook.", e);
            }
        }
        double duration = perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.COMPILE) / 1000.00;
        ImmutableMap<String, Long> compileHMSTimings = dumpMetaCallTimingWithoutEx("compilation");
        queryDisplay.setHmsTimings(QueryDisplay.Phase.COMPILATION, compileHMSTimings);
        boolean isInterrupted = lDrvState.isAborted();
        if (isInterrupted && !deferClose) {
            closeInProcess(true);
        }
        lDrvState.stateLock.lock();
        try {
            if (isInterrupted) {
                lDrvState.driverState = deferClose ? DriverState.EXECUTING : DriverState.ERROR;
            } else {
                lDrvState.driverState = compileError ? DriverState.ERROR : DriverState.COMPILED;
            }
        } finally {
            lDrvState.stateLock.unlock();
        }
        if (isInterrupted) {
            LOG.info("Compiling command(queryId=" + queryId + ") has been interrupted after " + duration + " seconds");
        } else {
            LOG.info("Completed compiling command(queryId=" + queryId + "); Time taken: " + duration + " seconds");
        }
    }
}
Also used : HiveSemanticAnalyzerHookContext(org.apache.hadoop.hive.ql.parse.HiveSemanticAnalyzerHookContext) BaseSemanticAnalyzer(org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer) AuthorizationException(org.apache.hadoop.hive.ql.metadata.AuthorizationException) HiveVariableSource(org.apache.hadoop.hive.conf.HiveVariableSource) CommandProcessorResponse(org.apache.hadoop.hive.ql.processors.CommandProcessorResponse) PerfLogger(org.apache.hadoop.hive.ql.log.PerfLogger) Configurable(org.apache.hadoop.conf.Configurable) LockException(org.apache.hadoop.hive.ql.lockmgr.LockException) ASTNode(org.apache.hadoop.hive.ql.parse.ASTNode) PrivateHookContext(org.apache.hadoop.hive.ql.hooks.PrivateHookContext) ParseContext(org.apache.hadoop.hive.ql.parse.ParseContext) HiveAuthzContext(org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzContext) WmContext(org.apache.hadoop.hive.ql.wm.WmContext) HookContext(org.apache.hadoop.hive.ql.hooks.HookContext) HiveSemanticAnalyzerHookContext(org.apache.hadoop.hive.ql.parse.HiveSemanticAnalyzerHookContext) VariableSubstitution(org.apache.hadoop.hive.conf.VariableSubstitution) LockException(org.apache.hadoop.hive.ql.lockmgr.LockException) IOException(java.io.IOException) ParseException(org.apache.hadoop.hive.ql.parse.ParseException) HiveException(org.apache.hadoop.hive.ql.metadata.HiveException) AuthorizationException(org.apache.hadoop.hive.ql.metadata.AuthorizationException) HiveSemanticAnalyzerHookContextImpl(org.apache.hadoop.hive.ql.parse.HiveSemanticAnalyzerHookContextImpl) HiveTxnManager(org.apache.hadoop.hive.ql.lockmgr.HiveTxnManager) ParseException(org.apache.hadoop.hive.ql.parse.ParseException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap)

Example 2 with LockException

use of org.apache.hadoop.hive.ql.lockmgr.LockException in project hive by apache.

the class DDLSemanticAnalyzer method analyzeShowDbLocks.

/**
 * Add the task according to the parsed command tree. This is used for the CLI
 * command "SHOW LOCKS DATABASE database [extended];".
 *
 * @param ast
 *          The parsed command tree.
 * @throws SemanticException
 *           Parsing failed
 */
private void analyzeShowDbLocks(ASTNode ast) throws SemanticException {
    boolean isExtended = (ast.getChildCount() > 1);
    String dbName = stripQuotes(ast.getChild(0).getText());
    HiveTxnManager txnManager = null;
    try {
        txnManager = TxnManagerFactory.getTxnManagerFactory().getTxnManager(conf);
    } catch (LockException e) {
        throw new SemanticException(e.getMessage());
    }
    ShowLocksDesc showLocksDesc = new ShowLocksDesc(ctx.getResFile(), dbName, isExtended, txnManager.useNewShowLocksFormat());
    rootTasks.add(TaskFactory.get(new DDLWork(getInputs(), getOutputs(), showLocksDesc)));
    setFetchTask(createFetchTask(showLocksDesc.getSchema()));
    // Need to initialize the lock manager
    ctx.setNeedLockMgr(true);
}
Also used : DDLWork(org.apache.hadoop.hive.ql.plan.DDLWork) LockException(org.apache.hadoop.hive.ql.lockmgr.LockException) ShowLocksDesc(org.apache.hadoop.hive.ql.plan.ShowLocksDesc) HiveTxnManager(org.apache.hadoop.hive.ql.lockmgr.HiveTxnManager)

Example 3 with LockException

use of org.apache.hadoop.hive.ql.lockmgr.LockException in project flink by apache.

the class HiveParser method startSessionState.

private void startSessionState(HiveConf hiveConf, CatalogManager catalogManager) {
    final ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
    try {
        HiveParserSessionState sessionState = new HiveParserSessionState(hiveConf, contextCL);
        sessionState.initTxnMgr(hiveConf);
        sessionState.setCurrentDatabase(catalogManager.getCurrentDatabase());
        // some Hive functions needs the timestamp
        setCurrentTimestamp(sessionState);
        SessionState.setCurrentSessionState(sessionState);
    } catch (LockException e) {
        throw new FlinkHiveException("Failed to init SessionState", e);
    } finally {
        // don't let SessionState mess up with our context classloader
        Thread.currentThread().setContextClassLoader(contextCL);
    }
}
Also used : LockException(org.apache.hadoop.hive.ql.lockmgr.LockException) FlinkHiveException(org.apache.flink.connectors.hive.FlinkHiveException)

Example 4 with LockException

use of org.apache.hadoop.hive.ql.lockmgr.LockException in project hive by apache.

the class AlterMaterializedViewRebuildAnalyzer method getRewrittenAST.

private ASTNode getRewrittenAST(TableName tableName) throws SemanticException {
    ASTNode rewrittenAST;
    // We need to go lookup the table and get the select statement and then parse it.
    try {
        Table table = getTableObjectByName(tableName.getNotEmptyDbTable(), true);
        if (!table.isMaterializedView()) {
            // Cannot rebuild not materialized view
            throw new SemanticException(ErrorMsg.REBUILD_NO_MATERIALIZED_VIEW);
        }
        // We need to use the expanded text for the materialized view, as it will contain
        // the qualified table aliases, etc.
        String viewText = table.getViewExpandedText();
        if (viewText.trim().isEmpty()) {
            throw new SemanticException(ErrorMsg.MATERIALIZED_VIEW_DEF_EMPTY);
        }
        Context ctx = new Context(queryState.getConf());
        String rewrittenInsertStatement = String.format(REWRITTEN_INSERT_STATEMENT, tableName.getEscapedNotEmptyDbTable(), viewText);
        rewrittenAST = ParseUtils.parse(rewrittenInsertStatement, ctx);
        this.ctx.addSubContext(ctx);
        if (!this.ctx.isExplainPlan() && AcidUtils.isTransactionalTable(table)) {
            // Acquire lock for the given materialized view. Only one rebuild per materialized view can be triggered at a
            // given time, as otherwise we might produce incorrect results if incremental maintenance is triggered.
            HiveTxnManager txnManager = getTxnMgr();
            LockState state;
            try {
                state = txnManager.acquireMaterializationRebuildLock(tableName.getDb(), tableName.getTable(), txnManager.getCurrentTxnId()).getState();
            } catch (LockException e) {
                throw new SemanticException("Exception acquiring lock for rebuilding the materialized view", e);
            }
            if (state != LockState.ACQUIRED) {
                throw new SemanticException("Another process is rebuilding the materialized view " + tableName.getNotEmptyDbTable());
            }
        }
    } catch (Exception e) {
        throw new SemanticException(e);
    }
    return rewrittenAST;
}
Also used : Context(org.apache.hadoop.hive.ql.Context) RelOptHiveTable(org.apache.hadoop.hive.ql.optimizer.calcite.RelOptHiveTable) Table(org.apache.hadoop.hive.ql.metadata.Table) LockException(org.apache.hadoop.hive.ql.lockmgr.LockException) ASTNode(org.apache.hadoop.hive.ql.parse.ASTNode) HiveTxnManager(org.apache.hadoop.hive.ql.lockmgr.HiveTxnManager) LockState(org.apache.hadoop.hive.metastore.api.LockState) SemanticException(org.apache.hadoop.hive.ql.parse.SemanticException) LockException(org.apache.hadoop.hive.ql.lockmgr.LockException) HiveException(org.apache.hadoop.hive.ql.metadata.HiveException) ColumnPropagationException(org.apache.hadoop.hive.ql.optimizer.calcite.rules.views.ColumnPropagationException) SemanticException(org.apache.hadoop.hive.ql.parse.SemanticException)

Example 5 with LockException

use of org.apache.hadoop.hive.ql.lockmgr.LockException in project hive by apache.

the class DriverTxnHandler method createTxnManager.

void createTxnManager() throws CommandProcessorException {
    try {
        // Initialize the transaction manager.  This must be done before analyze is called.
        HiveTxnManager queryTxnManager = (driverContext.getInitTxnManager() != null) ? driverContext.getInitTxnManager() : SessionState.get().initTxnMgr(driverContext.getConf());
        if (queryTxnManager instanceof Configurable) {
            ((Configurable) queryTxnManager).setConf(driverContext.getConf());
        }
        driverContext.setTxnManager(queryTxnManager);
        driverContext.getQueryState().setTxnManager(queryTxnManager);
        // In case when user Ctrl-C twice to kill Hive CLI JVM, we want to release locks
        // if compile is being called multiple times, clear the old shutdownhook
        ShutdownHookManager.removeShutdownHook(txnRollbackRunner);
        txnRollbackRunner = new Runnable() {

            @Override
            public void run() {
                try {
                    endTransactionAndCleanup(false, driverContext.getTxnManager());
                } catch (LockException e) {
                    LOG.warn("Exception when releasing locks in ShutdownHook for Driver: " + e.getMessage());
                }
            }
        };
        ShutdownHookManager.addShutdownHook(txnRollbackRunner, SHUTDOWN_HOOK_PRIORITY);
    } catch (LockException e) {
        ErrorMsg error = ErrorMsg.getErrorMsg(e.getMessage());
        String errorMessage = "FAILED: " + e.getClass().getSimpleName() + " [Error " + error.getErrorCode() + "]:";
        CONSOLE.printError(errorMessage, "\n" + StringUtils.stringifyException(e));
        throw DriverUtils.createProcessorException(driverContext, error.getErrorCode(), errorMessage, error.getSQLState(), e);
    }
}
Also used : LockException(org.apache.hadoop.hive.ql.lockmgr.LockException) HiveTxnManager(org.apache.hadoop.hive.ql.lockmgr.HiveTxnManager) Configurable(org.apache.hadoop.conf.Configurable)

Aggregations

LockException (org.apache.hadoop.hive.ql.lockmgr.LockException)15 HiveTxnManager (org.apache.hadoop.hive.ql.lockmgr.HiveTxnManager)7 HiveException (org.apache.hadoop.hive.ql.metadata.HiveException)6 IOException (java.io.IOException)4 Path (org.apache.hadoop.fs.Path)4 WriteEntity (org.apache.hadoop.hive.ql.hooks.WriteEntity)4 Partition (org.apache.hadoop.hive.ql.metadata.Partition)4 LoadTableDesc (org.apache.hadoop.hive.ql.plan.LoadTableDesc)4 FieldSchema (org.apache.hadoop.hive.metastore.api.FieldSchema)3 ImmutableMap (com.google.common.collect.ImmutableMap)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 List (java.util.List)2 Map (java.util.Map)2 Configurable (org.apache.hadoop.conf.Configurable)2 FileStatus (org.apache.hadoop.fs.FileStatus)2 ValidTxnWriteIdList (org.apache.hadoop.hive.common.ValidTxnWriteIdList)2