<commit_before>/*
 * Copyright 2017 Lithium Technologies, Inc.
 *
 * Licensed 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 com.lithium.flow.runner;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singletonList;

import com.lithium.flow.config.Config;
import com.lithium.flow.config.ConfigBuilder;
import com.lithium.flow.config.ConfigLoader;
import com.lithium.flow.config.Configs;
import com.lithium.flow.config.loaders.FileConfigLoader;
import com.lithium.flow.filer.Filer;
import com.lithium.flow.filer.RecordPath;
import com.lithium.flow.io.Swallower;
import com.lithium.flow.shell.Exec;
import com.lithium.flow.shell.Shell;
import com.lithium.flow.util.HostUtils;
import com.lithium.flow.util.Logs;
import com.lithium.flow.util.Main;
import com.lithium.flow.util.Needle;
import com.lithium.flow.util.Sleep;
import com.lithium.flow.util.Threader;
import com.lithium.flow.util.Unchecked;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;

/**
 * @author <NAME>
 */
public class RunnerMain {
	private static final Logger log = Logs.getLogger();

	private final Config runnerConfig;
	private final Filer destFiler;
	private final VaultRun vaultRun;
	private final RunnerContext context;
	private final String host;
	private Needle runNeedle;
	private Exec runExec;

	public RunnerMain(@Nonnull Config config, @Nonnull Config deployConfig, @Nonnull RunnerContext context)
			throws IOException {
		checkNotNull(config);
		checkNotNull(deployConfig);
		this.context = checkNotNull(context);

		runnerConfig = config.toBuilder().addAll(subConfig(deployConfig, "runner")).build();

		String name = runnerConfig.getString("name");
		host = runnerConfig.getString("host");
		String user = context.getAccess().getLogin(host).getUser();
		log.info("deploying {} to {}@{}", name, user, host);

		vaultRun = new VaultRun(context.getVault(), context.getAccess().getPrompt(), runnerConfig);

		destFiler = new FasterShellFiler(getShell().getFiler(), this::getShell);

		if (runnerConfig.getBoolean("kill.only", false)) {
			kill();
			return;
		}

		RunnerSync sync = new RunnerSync(runnerConfig, context, destFiler);
		sync.sync();

		kill();

		deploy(deployConfig);
	}

	@Nonnull
	private Shell getShell() throws IOException {
		return context.getShore().getShell(host);
	}

	public void deploy(@Nonnull Config deployConfig) throws IOException {
		vaultRun.deploy(destFiler);

		String configOut = runnerConfig.getString("config.out");
		destFiler.createDirs(RecordPath.getFolder(configOut));
		writeConfig(deployConfig, destFiler.writeFile(configOut));
		log.debug("wrote: {}", configOut);

		String classpath = Joiner.on(":").join(context.getClasspath(runnerConfig.getString("dest.dir")));
		log.debug("classpath: {}", classpath);

		for (String dir : runnerConfig.getList("dirs", Configs.emptyList())) {
			destFiler.createDirs(dir);
		}

		installJava();

		destFiler.close();

		context.getHostsMeasure().incDone();

		if (!runnerConfig.getBoolean("run", true)) {
			return;
		}

		String prefix = StringUtils.rightPad(runnerConfig.getString("name"), 15, '.') + " ";
		run(prefix, classpath, vaultRun.getEnv());
	}

	private void run(@Nonnull String prefix, @Nonnull String classpath, @Nullable String env) {
		try {
			runNeedle = context.getRunThreader().needle();

			List<String> commands = new ArrayList<>();
			commands.add("export CLASSPATH=" + classpath);
			if (env != null) {
				commands.add(env);
			}
			commands.add("cd " + runnerConfig.getString("dest.dir"));
			for (String link : runnerConfig.getList("links", Configs.emptyList())) {
				Iterator<String> it = Splitter.on(':').split(link).iterator();
				String target = it.next();
				String linkName = it.next();
				commands.add("rm -f " + linkName);
				commands.add("ln -sf " + target + " " + linkName);
			}

			String command = runnerConfig.getString("java.command");
			if (runnerConfig.getTime("relay", "0") > 0) {
				commands.add("export RELAY_COMMAND='" + command + "'");
				commands.add(runnerConfig.getString("relay.command"));
			} else {
				commands.add(command);
			}

			String readyString = runnerConfig.getString("run.readyString", null);
			AtomicBoolean ready = new AtomicBoolean();<commit_msg>Added runner prefix config options to allow custom logging<commit_after>/*
 * Copyright 2017 Lithium Technologies, Inc.
 *
 * Licensed 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 com.lithium.flow.runner;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singletonList;

import com.lithium.flow.config.Config;
import com.lithium.flow.config.ConfigBuilder;
import com.lithium.flow.config.ConfigLoader;
import com.lithium.flow.config.Configs;
import com.lithium.flow.config.loaders.FileConfigLoader;
import com.lithium.flow.filer.Filer;
import com.lithium.flow.filer.RecordPath;
import com.lithium.flow.io.Swallower;
import com.lithium.flow.shell.Exec;
import com.lithium.flow.shell.Shell;
import com.lithium.flow.util.HostUtils;
import com.lithium.flow.util.Logs;
import com.lithium.flow.util.Main;
import com.lithium.flow.util.Needle;
import com.lithium.flow.util.Sleep;
import com.lithium.flow.util.Threader;
import com.lithium.flow.util.Unchecked;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;

/**
 * @author <NAME>
 */
public class RunnerMain {
	private static final Logger log = Logs.getLogger();

	private final Config runnerConfig;
	private final Filer destFiler;
	private final VaultRun vaultRun;
	private final RunnerContext context;
	private final String host;
	private Needle runNeedle;
	private Exec runExec;

	public RunnerMain(@Nonnull Config config, @Nonnull Config deployConfig, @Nonnull RunnerContext context)
			throws IOException {
		checkNotNull(config);
		checkNotNull(deployConfig);
		this.context = checkNotNull(context);

		runnerConfig = config.toBuilder().addAll(subConfig(deployConfig, "runner")).build();

		String name = runnerConfig.getString("name");
		host = runnerConfig.getString("host");
		String user = context.getAccess().getLogin(host).getUser();
		log.info("deploying {} to {}@{}", name, user, host);

		vaultRun = new VaultRun(context.getVault(), context.getAccess().getPrompt(), runnerConfig);

		destFiler = new FasterShellFiler(getShell().getFiler(), this::getShell);

		if (runnerConfig.getBoolean("kill.only", false)) {
			kill();
			return;
		}

		RunnerSync sync = new RunnerSync(runnerConfig, context, destFiler);
		sync.sync();

		kill();

		deploy(deployConfig);
	}

	@Nonnull
	private Shell getShell() throws IOException {
		return context.getShore().getShell(host);
	}

	public void deploy(@Nonnull Config deployConfig) throws IOException {
		vaultRun.deploy(destFiler);

		String configOut = runnerConfig.getString("config.out");
		destFiler.createDirs(RecordPath.getFolder(configOut));
		writeConfig(deployConfig, destFiler.writeFile(configOut));
		log.debug("wrote: {}", configOut);

		String classpath = Joiner.on(":").join(context.getClasspath(runnerConfig.getString("dest.dir")));
		log.debug("classpath: {}", classpath);

		for (String dir : runnerConfig.getList("dirs", Configs.emptyList())) {
			destFiler.createDirs(dir);
		}

		installJava();

		destFiler.close();

		context.getHostsMeasure().incDone();

		if (!runnerConfig.getBoolean("run", true)) {
			return;
		}

		String prefix = runnerConfig.getString("prefix", runnerConfig.getString("name"));
		int pad = runnerConfig.getInt("prefixPad", 15);
		String paddedPrefix = StringUtils.rightPad(prefix, pad, '.') + " ";
		run(paddedPrefix, classpath, vaultRun.getEnv());
	}

	private void run(@Nonnull String prefix, @Nonnull String classpath, @Nullable String env) {
		try {
			runNeedle = context.getRunThreader().needle();

			List<String> commands = new ArrayList<>();
			commands.add("export CLASSPATH=" + classpath);
			if (env != null) {
				commands.add(env);
			}
			commands.add("cd " + runnerConfig.getString("dest.dir"));
			for (String link : runnerConfig.getList("links", Configs.emptyList())) {
				Iterator<String> it = Splitter.on(':').split(link).iterator();
				String target = it.next();
				String linkName = it.next();
				commands.add("rm -f " + linkName);
				commands.add("ln -sf " + target + " " + linkName);
			}

			String command = runnerConfig.getString("java.command");
			if (runnerConfig.getTime("relay", "0") > 0) {
				commands.add("export RELAY_COMMAND='" + command + "'");
				commands.add(runnerConfig.getString("relay.command"));
			} else {
				commands.add(command);
			}

			String readyString = runnerConfig.getString("run.readyString", null);
			AtomicBoolean ready = new AtomicBoolean();
{'fraction_non_alphanumeric': 0.13113539544360067, 'fraction_numerical': 0.0027782922763474717, 'mean_word_length': 4.8978700163844895, 'pattern_counts': {'":': 2, '<': 11, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4819118', 'n_tokens_mistral': 3566, 'n_tokens_neox': 3288, 'n_words': 761}