Search in sources :

Example 6 with NamedParamsDefault

use of org.pentaho.di.core.parameters.NamedParamsDefault in project pentaho-kettle by pentaho.

the class TransMeta method clear.

/**
 * Clears the transformation's meta-data, including the lists of databases, steps, hops, notes, dependencies,
 * partition schemas, slave servers, and cluster schemas. Logging information and timeouts are reset to defaults, and
 * recent connection info is cleared.
 */
@Override
public void clear() {
    setObjectId(null);
    steps = new ArrayList<>();
    hops = new ArrayList<>();
    dependencies = new ArrayList<>();
    partitionSchemas = new ArrayList<>();
    clusterSchemas = new ArrayList<>();
    namedParams = new NamedParamsDefault();
    stepChangeListeners = new ArrayList<>();
    slaveStepCopyPartitionDistribution = new SlaveStepCopyPartitionDistribution();
    trans_status = -1;
    trans_version = null;
    transLogTable = TransLogTable.getDefault(this, this, steps);
    performanceLogTable = PerformanceLogTable.getDefault(this, this);
    stepLogTable = StepLogTable.getDefault(this, this);
    metricsLogTable = MetricsLogTable.getDefault(this, this);
    sizeRowset = Const.ROWS_IN_ROWSET;
    sleepTimeEmpty = Const.TIMEOUT_GET_MILLIS;
    sleepTimeFull = Const.TIMEOUT_PUT_MILLIS;
    maxDateConnection = null;
    maxDateTable = null;
    maxDateField = null;
    maxDateOffset = 0.0;
    maxDateDifference = 0.0;
    undo = new ArrayList<>();
    max_undo = Const.MAX_UNDO;
    undo_position = -1;
    counters = new Hashtable<>();
    resultRows = null;
    super.clear();
    // LOAD THE DATABASE CACHE!
    dbCache = DBCache.getInstance();
    resultRows = new ArrayList<>();
    resultFiles = new ArrayList<>();
    feedbackShown = true;
    feedbackSize = Const.ROWS_UPDATE;
    // Thread priority:
    // - set to false in version 2.5.0
    // - re-enabling in version 3.0.1 to prevent excessive locking (PDI-491)
    // 
    usingThreadPriorityManagment = true;
    // The performance monitoring options
    // 
    capturingStepPerformanceSnapShots = false;
    // every 1 seconds
    stepPerformanceCapturingDelay = 1000;
    // maximum 100 data points
    stepPerformanceCapturingSizeLimit = "100";
    stepsFieldsCache = new HashMap<>();
    loopCache = new HashMap<>();
    previousStepCache = new HashMap<>();
    transformationType = TransformationType.Normal;
    log = LogChannel.GENERAL;
}
Also used : NamedParamsDefault(org.pentaho.di.core.parameters.NamedParamsDefault)

Example 7 with NamedParamsDefault

use of org.pentaho.di.core.parameters.NamedParamsDefault in project pentaho-kettle by pentaho.

the class Kitchen method main.

public static void main(String[] a) throws Exception {
    final ExecutorService executor = ExecutorUtil.getExecutor();
    final RepositoryPluginType repositoryPluginType = RepositoryPluginType.getInstance();
    final Future<Map.Entry<KettlePluginException, Future<KettleException>>> repositoryRegisterFuture = executor.submit(new Callable<Map.Entry<KettlePluginException, Future<KettleException>>>() {

        @Override
        public Map.Entry<KettlePluginException, Future<KettleException>> call() throws Exception {
            PluginRegistry.addPluginType(repositoryPluginType);
            try {
                KettleClientEnvironment.getInstance().setClient(KettleClientEnvironment.ClientType.KITCHEN);
                KettleClientEnvironment.init();
            } catch (KettlePluginException e) {
                return new AbstractMap.SimpleImmutableEntry<KettlePluginException, Future<KettleException>>(e, null);
            }
            Future<KettleException> kettleEnvironmentInitFuture = executor.submit(new Callable<KettleException>() {

                @Override
                public KettleException call() throws Exception {
                    try {
                        KettleClientEnvironment.getInstance().setClient(KettleClientEnvironment.ClientType.KITCHEN);
                        KettleEnvironment.init();
                    } catch (KettleException e) {
                        return e;
                    }
                    return null;
                }
            });
            return new AbstractMap.SimpleImmutableEntry<KettlePluginException, Future<KettleException>>(null, kettleEnvironmentInitFuture);
        }
    });
    List<String> args = new ArrayList<String>();
    for (int i = 0; i < a.length; i++) {
        if (a[i].length() > 0) {
            args.add(a[i]);
        }
    }
    DelegatingMetaStore metaStore = new DelegatingMetaStore();
    metaStore.addMetaStore(MetaStoreConst.openLocalPentahoMetaStore());
    metaStore.setActiveMetaStoreName(metaStore.getName());
    RepositoryMeta repositoryMeta = null;
    Job job = null;
    StringBuilder optionRepname, optionUsername, optionTrustUser, optionPassword, optionJobname, optionDirname, initialDir;
    StringBuilder optionFilename, optionLoglevel, optionLogfile, optionLogfileOld, optionListdir;
    StringBuilder optionListjobs, optionListrep, optionNorep, optionVersion, optionListParam, optionExport;
    NamedParams optionParams = new NamedParamsDefault();
    NamedParams customOptions = new NamedParamsDefault();
    CommandLineOption maxLogLinesOption = new CommandLineOption("maxloglines", BaseMessages.getString(PKG, "Kitchen.CmdLine.MaxLogLines"), new StringBuilder());
    CommandLineOption maxLogTimeoutOption = new CommandLineOption("maxlogtimeout", BaseMessages.getString(PKG, "Kitchen.CmdLine.MaxLogTimeout"), new StringBuilder());
    CommandLineOption[] options = new CommandLineOption[] { new CommandLineOption("rep", BaseMessages.getString(PKG, "Kitchen.CmdLine.RepName"), optionRepname = new StringBuilder()), new CommandLineOption("user", BaseMessages.getString(PKG, "Kitchen.CmdLine.RepUsername"), optionUsername = new StringBuilder()), new CommandLineOption("trustuser", BaseMessages.getString(PKG, "Kitchen.ComdLine.RepUsername"), optionTrustUser = new StringBuilder()), new CommandLineOption("pass", BaseMessages.getString(PKG, "Kitchen.CmdLine.RepPassword"), optionPassword = new StringBuilder()), new CommandLineOption("job", BaseMessages.getString(PKG, "Kitchen.CmdLine.RepJobName"), optionJobname = new StringBuilder()), new CommandLineOption("dir", BaseMessages.getString(PKG, "Kitchen.CmdLine.RepDir"), optionDirname = new StringBuilder()), new CommandLineOption("file", BaseMessages.getString(PKG, "Kitchen.CmdLine.XMLJob"), optionFilename = new StringBuilder()), new CommandLineOption("level", BaseMessages.getString(PKG, "Kitchen.CmdLine.LogLevel"), optionLoglevel = new StringBuilder()), new CommandLineOption("logfile", BaseMessages.getString(PKG, "Kitchen.CmdLine.LogFile"), optionLogfile = new StringBuilder()), new CommandLineOption("log", BaseMessages.getString(PKG, "Kitchen.CmdLine.LogFileOld"), optionLogfileOld = new StringBuilder(), false, true), new CommandLineOption("listdir", BaseMessages.getString(PKG, "Kitchen.CmdLine.ListDir"), optionListdir = new StringBuilder(), true, false), new CommandLineOption("listjobs", BaseMessages.getString(PKG, "Kitchen.CmdLine.ListJobsDir"), optionListjobs = new StringBuilder(), true, false), new CommandLineOption("listrep", BaseMessages.getString(PKG, "Kitchen.CmdLine.ListAvailableReps"), optionListrep = new StringBuilder(), true, false), new CommandLineOption("norep", BaseMessages.getString(PKG, "Kitchen.CmdLine.NoRep"), optionNorep = new StringBuilder(), true, false), new CommandLineOption("version", BaseMessages.getString(PKG, "Kitchen.CmdLine.Version"), optionVersion = new StringBuilder(), true, false), new CommandLineOption("param", BaseMessages.getString(PKG, "Kitchen.ComdLine.Param"), optionParams, false), new CommandLineOption("listparam", BaseMessages.getString(PKG, "Kitchen.ComdLine.ListParam"), optionListParam = new StringBuilder(), true, false), new CommandLineOption("export", BaseMessages.getString(PKG, "Kitchen.ComdLine.Export"), optionExport = new StringBuilder(), true, false), new CommandLineOption("initialDir", null, initialDir = new StringBuilder(), false, true), new CommandLineOption("custom", BaseMessages.getString(PKG, "Kitchen.ComdLine.Custom"), customOptions, false), maxLogLinesOption, maxLogTimeoutOption };
    if (args.size() == 2) {
        // 2 internal hidden argument (flag and value)
        CommandLineOption.printUsage(options);
        exitJVM(9);
    }
    LogChannelInterface log = new LogChannel(STRING_KITCHEN);
    CommandLineOption.parseArguments(args, options, log);
    configureLogging(maxLogLinesOption, maxLogTimeoutOption);
    String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null);
    String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null);
    String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null);
    if (!Utils.isEmpty(kettleRepname)) {
        optionRepname = new StringBuilder(kettleRepname);
    }
    if (!Utils.isEmpty(kettleUsername)) {
        optionUsername = new StringBuilder(kettleUsername);
    }
    if (!Utils.isEmpty(kettlePassword)) {
        optionPassword = new StringBuilder(kettlePassword);
    }
    if (Utils.isEmpty(optionLogfile) && !Utils.isEmpty(optionLogfileOld)) {
        // if the old style of logging name is filled in, and the new one is not
        // overwrite the new by the old
        optionLogfile = optionLogfileOld;
    }
    Map.Entry<KettlePluginException, Future<KettleException>> repositoryRegisterResults = repositoryRegisterFuture.get();
    // It's a singleton map with one key-value pair (a Pair collection)
    KettlePluginException repositoryRegisterException = repositoryRegisterResults.getKey();
    if (repositoryRegisterException != null) {
        throw repositoryRegisterException;
    }
    Future<KettleException> kettleInitFuture = repositoryRegisterResults.getValue();
    if (!Utils.isEmpty(optionLogfile)) {
        fileAppender = new FileLoggingEventListener(optionLogfile.toString(), true);
        KettleLogStore.getAppender().addLoggingEventListener(fileAppender);
    } else {
        fileAppender = null;
    }
    if (!Utils.isEmpty(optionLoglevel)) {
        log.setLogLevel(LogLevel.getLogLevelForCode(optionLoglevel.toString()));
        log.logMinimal(BaseMessages.getString(PKG, "Kitchen.Log.LogLevel", log.getLogLevel().getDescription()));
    }
    // Start the action...
    // 
    int returnCode = CommandExecutorCodes.Kitchen.SUCCESS.getCode();
    try {
        if (getCommandExecutor() == null) {
            // init
            setCommandExecutor(new KitchenCommandExecutor(PKG, log, kettleInitFuture));
        }
        if (!Utils.isEmpty(optionVersion)) {
            getCommandExecutor().printVersion();
            if (a.length == 1) {
                exitJVM(CommandExecutorCodes.Pan.KETTLE_VERSION_PRINT.getCode());
            }
        }
        returnCode = getCommandExecutor().execute(optionRepname.toString(), optionNorep.toString(), optionUsername.toString(), optionTrustUser.toString(), optionPassword.toString(), optionDirname.toString(), optionFilename.toString(), optionJobname.toString(), optionListjobs.toString(), optionListdir.toString(), optionExport.toString(), initialDir.toString(), optionListrep.toString(), optionListParam.toString(), optionParams, customOptions, args.toArray(new String[args.size()]));
    } catch (Throwable t) {
        t.printStackTrace();
        returnCode = CommandExecutorCodes.Pan.UNEXPECTED_ERROR.getCode();
    } finally {
        if (fileAppender != null) {
            fileAppender.close();
            KettleLogStore.getAppender().removeLoggingEventListener(fileAppender);
        }
    }
    exitJVM(returnCode);
}
Also used : KettleException(org.pentaho.di.core.exception.KettleException) NamedParams(org.pentaho.di.core.parameters.NamedParams) RepositoryPluginType(org.pentaho.di.core.plugins.RepositoryPluginType) ArrayList(java.util.ArrayList) Callable(java.util.concurrent.Callable) AbstractMap(java.util.AbstractMap) RepositoryMeta(org.pentaho.di.repository.RepositoryMeta) CommandLineOption(org.pentaho.di.pan.CommandLineOption) Job(org.pentaho.di.job.Job) NamedParamsDefault(org.pentaho.di.core.parameters.NamedParamsDefault) KettlePluginException(org.pentaho.di.core.exception.KettlePluginException) FileLoggingEventListener(org.pentaho.di.core.logging.FileLoggingEventListener) LogChannel(org.pentaho.di.core.logging.LogChannel) DelegatingMetaStore(org.pentaho.metastore.stores.delegate.DelegatingMetaStore) KettleException(org.pentaho.di.core.exception.KettleException) ExecutionException(java.util.concurrent.ExecutionException) KettlePluginException(org.pentaho.di.core.exception.KettlePluginException) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) LogChannelInterface(org.pentaho.di.core.logging.LogChannelInterface) Map(java.util.Map) AbstractMap(java.util.AbstractMap)

Example 8 with NamedParamsDefault

use of org.pentaho.di.core.parameters.NamedParamsDefault in project pentaho-kettle by pentaho.

the class JobEntryJob method execute.

@Override
public Result execute(Result result, int nr) throws KettleException {
    result.setEntryNr(nr);
    LogChannelFileWriter logChannelFileWriter = null;
    LogLevel jobLogLevel = parentJob.getLogLevel();
    // Set Embedded NamedCluter MetatStore Provider Key so that it can be passed to VFS
    if (parentJobMeta.getNamedClusterEmbedManager() != null) {
        parentJobMeta.getNamedClusterEmbedManager().passEmbeddedMetastoreKey(this, parentJobMeta.getEmbeddedMetastoreProviderKey());
    }
    if (setLogfile) {
        String realLogFilename = environmentSubstitute(getLogFilename());
        // if we do not have one, we must fail
        if (Utils.isEmpty(realLogFilename)) {
            logError(BaseMessages.getString(PKG, "JobJob.Exception.LogFilenameMissing"));
            result.setNrErrors(1);
            result.setResult(false);
            return result;
        }
        // create parent folder?
        if (!createParentFolder(realLogFilename)) {
            result.setNrErrors(1);
            result.setResult(false);
            return result;
        }
        try {
            logChannelFileWriter = new LogChannelFileWriter(this.getLogChannelId(), KettleVFS.getFileObject(realLogFilename), setAppendLogfile);
            logChannelFileWriter.startLogging();
        } catch (KettleException e) {
            logError("Unable to open file appender for file [" + getLogFilename() + "] : " + e.toString());
            logError(Const.getStackTracker(e));
            result.setNrErrors(1);
            result.setResult(false);
            return result;
        }
        jobLogLevel = logFileLevel;
    }
    try {
        // First load the job, outside of the loop...
        if (parentJob.getJobMeta() != null) {
            // reset the internal variables again.
            // Maybe we should split up the variables even more like in UNIX shells.
            // The internal variables need to be reset to be able use them properly
            // in 2 sequential sub jobs.
            parentJob.getJobMeta().setInternalKettleVariables();
        }
        // 
        switch(specificationMethod) {
            case REPOSITORY_BY_NAME:
                if (log.isDetailed()) {
                    logDetailed("Loading job from repository : [" + directory + " : " + environmentSubstitute(jobname) + "]");
                }
                break;
            case FILENAME:
                if (log.isDetailed()) {
                    logDetailed("Loading job from XML file : [" + environmentSubstitute(filename) + "]");
                }
                break;
            case REPOSITORY_BY_REFERENCE:
                if (log.isDetailed()) {
                    logDetailed("Loading job from repository by reference : [" + jobObjectId + "]");
                }
                break;
            default:
                break;
        }
        JobMeta jobMeta = getJobMeta(rep, this);
        // 
        if (jobMeta == null) {
            throw new KettleException("Unable to load the job: please specify the name and repository directory OR a filename");
        }
        verifyRecursiveExecution(parentJob, jobMeta);
        int iteration = 0;
        String[] args1 = arguments;
        // no arguments? Check the parent jobs arguments
        if (args1 == null || args1.length == 0) {
            args1 = parentJob.getArguments();
        }
        copyVariablesFrom(parentJob);
        setParentVariableSpace(parentJob);
        // 
        // For the moment only do variable translation at the start of a job, not
        // for every input row (if that would be switched on)
        // 
        String[] args = null;
        if (args1 != null) {
            args = new String[args1.length];
            for (int idx = 0; idx < args1.length; idx++) {
                args[idx] = environmentSubstitute(args1[idx]);
            }
        }
        RowMetaAndData resultRow = null;
        boolean first = true;
        List<RowMetaAndData> rows = new ArrayList<RowMetaAndData>(result.getRows());
        while ((first && !execPerRow) || (execPerRow && rows != null && iteration < rows.size() && result.getNrErrors() == 0)) {
            first = false;
            // 
            if (execPerRow) {
                result.getRows().clear();
            }
            if (rows != null && execPerRow) {
                resultRow = rows.get(iteration);
            } else {
                resultRow = null;
            }
            NamedParams namedParam = new NamedParamsDefault();
            // 
            if (paramsFromPrevious) {
                String[] parentParameters = parentJob.listParameters();
                for (int idx = 0; idx < parentParameters.length; idx++) {
                    String par = parentParameters[idx];
                    String def = parentJob.getParameterDefault(par);
                    String val = parentJob.getParameterValue(par);
                    String des = parentJob.getParameterDescription(par);
                    namedParam.addParameterDefinition(par, def, des);
                    namedParam.setParameterValue(par, val);
                }
            }
            // 
            if (parameters != null) {
                for (int idx = 0; idx < parameters.length; idx++) {
                    if (!Utils.isEmpty(parameters[idx])) {
                        // 
                        if (Const.indexOfString(parameters[idx], namedParam.listParameters()) < 0) {
                            // We have a parameter
                            try {
                                namedParam.addParameterDefinition(parameters[idx], "", "Job entry runtime");
                            } catch (DuplicateParamException e) {
                                // Should never happen
                                // 
                                logError("Duplicate parameter definition for " + parameters[idx]);
                            }
                        }
                        if (Utils.isEmpty(Const.trim(parameterFieldNames[idx]))) {
                            namedParam.setParameterValue(parameters[idx], Const.NVL(environmentSubstitute(parameterValues[idx]), ""));
                        } else {
                            // something filled in, in the field column...
                            // 
                            String value = "";
                            if (resultRow != null) {
                                value = resultRow.getString(parameterFieldNames[idx], "");
                            }
                            namedParam.setParameterValue(parameters[idx], value);
                        }
                    }
                }
            }
            Result oneResult = new Result();
            List<RowMetaAndData> sourceRows = null;
            if (execPerRow) {
                if (argFromPrevious) {
                    // Copy the input row to the (command line) arguments
                    args = null;
                    if (resultRow != null) {
                        args = new String[resultRow.size()];
                        for (int i = 0; i < resultRow.size(); i++) {
                            args[i] = resultRow.getString(i, null);
                        }
                    }
                } else {
                    // Just pass a single row
                    List<RowMetaAndData> newList = new ArrayList<RowMetaAndData>();
                    newList.add(resultRow);
                    sourceRows = newList;
                }
                if (paramsFromPrevious) {
                    if (parameters != null) {
                        for (int idx = 0; idx < parameters.length; idx++) {
                            if (!Utils.isEmpty(parameters[idx])) {
                                // We have a parameter
                                if (Utils.isEmpty(Const.trim(parameterFieldNames[idx]))) {
                                    namedParam.setParameterValue(parameters[idx], Const.NVL(environmentSubstitute(parameterValues[idx]), ""));
                                } else {
                                    String fieldValue = "";
                                    if (resultRow != null) {
                                        fieldValue = resultRow.getString(parameterFieldNames[idx], "");
                                    }
                                    // Get the value from the input stream
                                    namedParam.setParameterValue(parameters[idx], Const.NVL(fieldValue, ""));
                                }
                            }
                        }
                    }
                }
            } else {
                if (argFromPrevious) {
                    // Only put the first Row on the arguments
                    args = null;
                    if (resultRow != null) {
                        args = new String[resultRow.size()];
                        for (int i = 0; i < resultRow.size(); i++) {
                            args[i] = resultRow.getString(i, null);
                        }
                    }
                } else {
                    // Keep it as it was...
                    sourceRows = result.getRows();
                }
                if (paramsFromPrevious) {
                    if (parameters != null) {
                        for (int idx = 0; idx < parameters.length; idx++) {
                            if (!Utils.isEmpty(parameters[idx])) {
                                // We have a parameter
                                if (Utils.isEmpty(Const.trim(parameterFieldNames[idx]))) {
                                    namedParam.setParameterValue(parameters[idx], Const.NVL(environmentSubstitute(parameterValues[idx]), ""));
                                } else {
                                    String fieldValue = "";
                                    if (resultRow != null) {
                                        fieldValue = resultRow.getString(parameterFieldNames[idx], "");
                                    }
                                    // Get the value from the input stream
                                    namedParam.setParameterValue(parameters[idx], Const.NVL(fieldValue, ""));
                                }
                            }
                        }
                    }
                }
            }
            boolean doFallback = true;
            SlaveServer remoteSlaveServer = null;
            JobExecutionConfiguration executionConfiguration = new JobExecutionConfiguration();
            if (!Utils.isEmpty(runConfiguration)) {
                log.logBasic(BaseMessages.getString(PKG, "JobJob.RunConfig.Message"), runConfiguration);
                runConfiguration = environmentSubstitute(runConfiguration);
                executionConfiguration.setRunConfiguration(runConfiguration);
                try {
                    ExtensionPointHandler.callExtensionPoint(log, KettleExtensionPoint.SpoonTransBeforeStart.id, new Object[] { executionConfiguration, parentJob.getJobMeta(), jobMeta, rep });
                    if (!executionConfiguration.isExecutingLocally() && !executionConfiguration.isExecutingRemotely()) {
                        result.setResult(true);
                        return result;
                    }
                    remoteSlaveServer = executionConfiguration.getRemoteServer();
                    doFallback = false;
                } catch (KettleException e) {
                    log.logError(e.getMessage(), getName());
                    result.setNrErrors(1);
                    result.setResult(false);
                    return result;
                }
            }
            if (doFallback) {
                // 
                if (!Utils.isEmpty(remoteSlaveServerName)) {
                    String realRemoteSlaveServerName = environmentSubstitute(remoteSlaveServerName);
                    remoteSlaveServer = parentJob.getJobMeta().findSlaveServer(realRemoteSlaveServerName);
                    if (remoteSlaveServer == null) {
                        throw new KettleException(BaseMessages.getString(PKG, "JobTrans.Exception.UnableToFindRemoteSlaveServer", realRemoteSlaveServerName));
                    }
                }
            }
            if (remoteSlaveServer == null) {
                // Local execution...
                // 
                // Create a new job
                // 
                job = new Job(rep, jobMeta, this);
                job.setParentJob(parentJob);
                job.setLogLevel(jobLogLevel);
                job.shareVariablesWith(this);
                job.setInternalKettleVariables(this);
                job.copyParametersFrom(jobMeta);
                job.setInteractive(parentJob.isInteractive());
                if (job.isInteractive()) {
                    job.getJobEntryListeners().addAll(parentJob.getJobEntryListeners());
                }
                // Pass the socket repository all around.
                // 
                job.setSocketRepository(parentJob.getSocketRepository());
                // Set the parameters calculated above on this instance.
                // 
                job.clearParameters();
                String[] parameterNames = job.listParameters();
                for (int idx = 0; idx < parameterNames.length; idx++) {
                    // Grab the parameter value set in the job entry
                    // 
                    String thisValue = namedParam.getParameterValue(parameterNames[idx]);
                    if (!Utils.isEmpty(thisValue)) {
                        // Set the value as specified by the user in the job entry
                        // 
                        job.setParameterValue(parameterNames[idx], thisValue);
                    } else {
                        // 
                        if (isPassingAllParameters()) {
                            String parentValue = parentJob.getParameterValue(parameterNames[idx]);
                            if (!Utils.isEmpty(parentValue)) {
                                job.setParameterValue(parameterNames[idx], parentValue);
                            }
                        }
                    }
                }
                job.activateParameters();
                // Set the source rows we calculated above...
                // 
                job.setSourceRows(sourceRows);
                // Don't forget the logging...
                job.beginProcessing();
                // Link the job with the sub-job
                parentJob.getJobTracker().addJobTracker(job.getJobTracker());
                // Link both ways!
                job.getJobTracker().setParentJobTracker(parentJob.getJobTracker());
                if (parentJob.getJobMeta().isBatchIdPassed()) {
                    job.setPassedBatchId(parentJob.getBatchId());
                }
                job.setArguments(args);
                // 
                for (DelegationListener delegationListener : parentJob.getDelegationListeners()) {
                    // TODO: copy some settings in the job execution configuration, not strictly needed
                    // but the execution configuration information is useful in case of a job re-start
                    // 
                    delegationListener.jobDelegationStarted(job, new JobExecutionConfiguration());
                }
                JobEntryJobRunner runner = new JobEntryJobRunner(job, result, nr, log);
                Thread jobRunnerThread = new Thread(runner);
                // PDI-6518
                // added UUID to thread name, otherwise threads do share names if jobs entries are executed in parallel in a
                // parent job
                // if that happens, contained transformations start closing each other's connections
                jobRunnerThread.setName(Const.NVL(job.getJobMeta().getName(), job.getJobMeta().getFilename()) + " UUID: " + UUID.randomUUID().toString());
                jobRunnerThread.start();
                // 
                while (!runner.isFinished() && !parentJob.isStopped()) {
                    try {
                        Thread.sleep(0, 1);
                    } catch (InterruptedException e) {
                    // Ignore
                    }
                }
                // if the parent-job was stopped, stop the sub-job too...
                if (parentJob.isStopped()) {
                    job.stopAll();
                    // Wait until finished!
                    runner.waitUntilFinished();
                }
                oneResult = runner.getResult();
            } else {
                // Make sure we can parameterize the slave server connection
                // 
                remoteSlaveServer.shareVariablesWith(this);
                // Remote execution...
                // 
                JobExecutionConfiguration jobExecutionConfiguration = new JobExecutionConfiguration();
                // lightClone() because rows are
                jobExecutionConfiguration.setPreviousResult(result.lightClone());
                // overwritten in next line.
                jobExecutionConfiguration.getPreviousResult().setRows(sourceRows);
                jobExecutionConfiguration.setArgumentStrings(args);
                jobExecutionConfiguration.setVariables(this);
                jobExecutionConfiguration.setRemoteServer(remoteSlaveServer);
                jobExecutionConfiguration.setRepository(rep);
                jobExecutionConfiguration.setLogLevel(jobLogLevel);
                jobExecutionConfiguration.setPassingExport(passingExport);
                jobExecutionConfiguration.setExpandingRemoteJob(expandingRemoteJob);
                for (String param : namedParam.listParameters()) {
                    String defValue = namedParam.getParameterDefault(param);
                    String value = namedParam.getParameterValue(param);
                    jobExecutionConfiguration.getParams().put(param, Const.NVL(value, defValue));
                }
                if (parentJob.getJobMeta().isBatchIdPassed()) {
                    jobExecutionConfiguration.setPassedBatchId(parentJob.getBatchId());
                }
                // Send the XML over to the slave server
                // Also start the job over there...
                // 
                String carteObjectId = null;
                try {
                    carteObjectId = Job.sendToSlaveServer(jobMeta, jobExecutionConfiguration, rep, metaStore);
                } catch (KettleException e) {
                    // Perhaps the job exists on the remote server, carte is down, etc.
                    // This is an abort situation, stop the parent job...
                    // We want this in case we are running in parallel. The other job
                    // entries can stop running now.
                    // 
                    parentJob.stopAll();
                    // 
                    throw e;
                }
                // Now start the monitoring...
                // 
                SlaveServerJobStatus jobStatus = null;
                while (!parentJob.isStopped() && waitingToFinish) {
                    try {
                        jobStatus = remoteSlaveServer.getJobStatus(jobMeta.getName(), carteObjectId, 0);
                        if (jobStatus.getResult() != null) {
                            // The job is finished, get the result...
                            // 
                            oneResult = jobStatus.getResult();
                            break;
                        }
                    } catch (Exception e1) {
                        logError("Unable to contact slave server [" + remoteSlaveServer + "] to verify the status of job [" + jobMeta.getName() + "]", e1);
                        oneResult.setNrErrors(1L);
                        // Stop looking too, chances are too low the server will
                        break;
                    // come back on-line
                    }
                    // sleep for 1 second
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    // Ignore
                    }
                }
                // Write log from carte to file
                if (setLogfile && jobStatus != null) {
                    String logFromCarte = jobStatus.getLoggingString();
                    if (!Utils.isEmpty(logFromCarte)) {
                        FileObject logfile = logChannelFileWriter.getLogFile();
                        OutputStream logFileOutputStream = null;
                        try {
                            logFileOutputStream = KettleVFS.getOutputStream(logfile, setAppendLogfile);
                            logFileOutputStream.write(logFromCarte.getBytes());
                            logFileOutputStream.flush();
                        } catch (Exception e) {
                            logError("There was an error logging to file '" + logfile + "'", e);
                        } finally {
                            try {
                                if (logFileOutputStream != null) {
                                    logFileOutputStream.close();
                                    logFileOutputStream = null;
                                }
                            } catch (Exception e) {
                                logError("There was an error closing log file file '" + logfile + "'", e);
                            }
                        }
                    }
                }
                if (!waitingToFinish) {
                    // Since the job was posted successfully, the result is true...
                    // 
                    oneResult = new Result();
                    oneResult.setResult(true);
                }
                if (parentJob.isStopped()) {
                    try {
                        // 
                        if (jobStatus == null || jobStatus.isRunning()) {
                            // Try a remote abort ...
                            // 
                            remoteSlaveServer.stopJob(jobMeta.getName(), carteObjectId);
                        }
                    } catch (Exception e1) {
                        logError("Unable to contact slave server [" + remoteSlaveServer + "] to stop job [" + jobMeta.getName() + "]", e1);
                        oneResult.setNrErrors(1L);
                        // Stop looking too, chances are too low the server will
                        break;
                    // come back on-line
                    }
                }
            }
            // clear only the numbers, NOT the files or rows.
            result.clear();
            result.add(oneResult);
            // Set the result rows too, if any ...
            if (!Utils.isEmpty(oneResult.getRows())) {
                result.setRows(new ArrayList<RowMetaAndData>(oneResult.getRows()));
            }
            // 
            if (oneResult.getResult() == false) {
                result.setNrErrors(result.getNrErrors() + 1);
            }
            iteration++;
        }
    } catch (KettleException ke) {
        logError("Error running job entry 'job' : ", ke);
        result.setResult(false);
        result.setNrErrors(1L);
    }
    if (setLogfile) {
        if (logChannelFileWriter != null) {
            logChannelFileWriter.stopLogging();
            ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, logChannelFileWriter.getLogFile(), parentJob.getJobname(), getName());
            result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
            // 
            if (logChannelFileWriter.getException() != null) {
                logError("Unable to open log file [" + getLogFilename() + "] : ");
                logError(Const.getStackTracker(logChannelFileWriter.getException()));
                result.setNrErrors(1);
                result.setResult(false);
                return result;
            }
        }
    }
    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }
    return result;
}
Also used : KettleException(org.pentaho.di.core.exception.KettleException) JobMeta(org.pentaho.di.job.JobMeta) DuplicateParamException(org.pentaho.di.core.parameters.DuplicateParamException) NamedParams(org.pentaho.di.core.parameters.NamedParams) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) SlaveServer(org.pentaho.di.cluster.SlaveServer) LogLevel(org.pentaho.di.core.logging.LogLevel) Result(org.pentaho.di.core.Result) SlaveServerJobStatus(org.pentaho.di.www.SlaveServerJobStatus) RowMetaAndData(org.pentaho.di.core.RowMetaAndData) FileObject(org.apache.commons.vfs2.FileObject) Job(org.pentaho.di.job.Job) NamedParamsDefault(org.pentaho.di.core.parameters.NamedParamsDefault) LogChannelFileWriter(org.pentaho.di.core.logging.LogChannelFileWriter) ResultFile(org.pentaho.di.core.ResultFile) JobExecutionConfiguration(org.pentaho.di.job.JobExecutionConfiguration) KettleExtensionPoint(org.pentaho.di.core.extension.KettleExtensionPoint) KettleXMLException(org.pentaho.di.core.exception.KettleXMLException) DuplicateParamException(org.pentaho.di.core.parameters.DuplicateParamException) KettleException(org.pentaho.di.core.exception.KettleException) KettleDatabaseException(org.pentaho.di.core.exception.KettleDatabaseException) DelegationListener(org.pentaho.di.job.DelegationListener)

Example 9 with NamedParamsDefault

use of org.pentaho.di.core.parameters.NamedParamsDefault in project pentaho-kettle by pentaho.

the class JobMeta method realClone.

/**
 * Perform a real clone of the job meta-data object, including cloning all lists and copying all values. If the
 * doClear parameter is true, the clone will be cleared of ALL values before the copy. If false, only the copied
 * fields will be cleared.
 *
 * @param doClear Whether to clear all of the clone's data before copying from the source object
 * @return a real clone of the calling object
 */
public Object realClone(boolean doClear) {
    try {
        JobMeta jobMeta = (JobMeta) super.clone();
        if (doClear) {
            jobMeta.clear();
        } else {
            jobMeta.jobcopies = new ArrayList<JobEntryCopy>();
            jobMeta.jobhops = new ArrayList<JobHopMeta>();
            jobMeta.notes = new ArrayList<NotePadMeta>();
            jobMeta.databases = new ArrayList<DatabaseMeta>();
            jobMeta.slaveServers = new ArrayList<SlaveServer>();
            jobMeta.namedParams = new NamedParamsDefault();
        }
        for (JobEntryCopy entry : jobcopies) {
            jobMeta.jobcopies.add((JobEntryCopy) entry.clone_deep());
        }
        for (JobHopMeta entry : jobhops) {
            jobMeta.jobhops.add((JobHopMeta) entry.clone());
        }
        for (NotePadMeta entry : notes) {
            jobMeta.notes.add((NotePadMeta) entry.clone());
        }
        for (DatabaseMeta entry : databases) {
            jobMeta.databases.add((DatabaseMeta) entry.clone());
        }
        for (SlaveServer slave : slaveServers) {
            jobMeta.getSlaveServers().add((SlaveServer) slave.clone());
        }
        for (String key : listParameters()) {
            jobMeta.addParameterDefinition(key, getParameterDefault(key), getParameterDescription(key));
        }
        return jobMeta;
    } catch (Exception e) {
        return null;
    }
}
Also used : NamedParamsDefault(org.pentaho.di.core.parameters.NamedParamsDefault) SlaveServer(org.pentaho.di.cluster.SlaveServer) DatabaseMeta(org.pentaho.di.core.database.DatabaseMeta) KettleXMLException(org.pentaho.di.core.exception.KettleXMLException) KettleFileException(org.pentaho.di.core.exception.KettleFileException) UnknownParamException(org.pentaho.di.core.parameters.UnknownParamException) LookupReferencesException(org.pentaho.di.core.exception.LookupReferencesException) FileSystemException(org.apache.commons.vfs2.FileSystemException) KettleException(org.pentaho.di.core.exception.KettleException) KettleDatabaseException(org.pentaho.di.core.exception.KettleDatabaseException) IdNotFoundException(org.pentaho.di.core.exception.IdNotFoundException) JobEntryCopy(org.pentaho.di.job.entry.JobEntryCopy) NotePadMeta(org.pentaho.di.core.NotePadMeta)

Aggregations

NamedParamsDefault (org.pentaho.di.core.parameters.NamedParamsDefault)9 NamedParams (org.pentaho.di.core.parameters.NamedParams)6 KettleException (org.pentaho.di.core.exception.KettleException)5 ArrayList (java.util.ArrayList)4 SlaveServer (org.pentaho.di.cluster.SlaveServer)4 KettleDatabaseException (org.pentaho.di.core.exception.KettleDatabaseException)4 KettleXMLException (org.pentaho.di.core.exception.KettleXMLException)4 Job (org.pentaho.di.job.Job)3 Trans (org.pentaho.di.trans.Trans)3 Map (java.util.Map)2 FileSystemException (org.apache.commons.vfs2.FileSystemException)2 Test (org.junit.Test)2 NotePadMeta (org.pentaho.di.core.NotePadMeta)2 Result (org.pentaho.di.core.Result)2 ResultFile (org.pentaho.di.core.ResultFile)2 RowMetaAndData (org.pentaho.di.core.RowMetaAndData)2 DatabaseMeta (org.pentaho.di.core.database.DatabaseMeta)2 KettleFileException (org.pentaho.di.core.exception.KettleFileException)2 KettleExtensionPoint (org.pentaho.di.core.extension.KettleExtensionPoint)2 FileLoggingEventListener (org.pentaho.di.core.logging.FileLoggingEventListener)2