hpcpack-linux-agent/nodemanager/core/Process.cpp

659 строки
20 KiB
C++
Исходник Постоянная ссылка Обычный вид История

2015-04-24 07:32:37 +03:00
#include <memory.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <fstream>
2015-05-14 15:18:59 +03:00
#include <cpprest/http_client.h>
#include <boost/algorithm/string/predicate.hpp>
2015-04-24 07:32:37 +03:00
#include "Process.h"
#include "../utils/Logger.h"
#include "../utils/String.h"
2015-04-24 07:32:37 +03:00
#include "../common/ErrorCodes.h"
#include "../utils/WriterLock.h"
2015-05-14 15:18:59 +03:00
#include "../data/OutputData.h"
2015-07-23 14:05:09 +03:00
#include "HttpHelper.h"
2015-04-24 07:32:37 +03:00
using namespace hpc::core;
using namespace hpc::utils;
2015-04-24 07:32:37 +03:00
using namespace hpc::common;
using namespace hpc::data;
2015-05-14 15:18:59 +03:00
using namespace http;
2015-04-24 07:32:37 +03:00
2015-04-08 16:39:42 +03:00
Process::Process(
2015-04-24 07:32:37 +03:00
int jobId,
2015-04-08 16:39:42 +03:00
int taskId,
2015-04-24 07:32:37 +03:00
int requeueCount,
const std::string& taskExecutionName,
2015-04-24 07:32:37 +03:00
const std::string& cmdLine,
const std::string& standardOut,
const std::string& standardErr,
const std::string& standardIn,
const std::string& workDir,
const std::string& user,
bool dumpStdoutToExecutionMessage,
2015-04-24 07:32:37 +03:00
std::vector<uint64_t>&& cpuAffinity,
std::map<std::string, std::string>&& envi,
2015-04-08 16:39:42 +03:00
const std::function<Callback> completed) :
jobId(jobId), taskId(taskId), requeueCount(requeueCount), taskExecutionId(String::Join("_", taskExecutionName, jobId, taskId, requeueCount)),
2015-04-24 07:32:37 +03:00
commandLine(cmdLine), stdOutFile(standardOut), stdErrFile(standardErr), stdInFile(standardIn),
2017-08-03 11:27:32 +03:00
workDirectory(workDir), userName(user.empty() ? "root" : user), dockerImage(envi["CCP_DOCKER_IMAGE"]), dumpStdout(dumpStdoutToExecutionMessage),
2015-04-24 07:32:37 +03:00
affinity(cpuAffinity), environments(envi), callback(completed), processId(0)
{
2017-09-11 12:39:42 +03:00
this->streamOutput = StartWithHttpOrHttps(stdOutFile);
2015-06-02 06:40:34 +03:00
Logger::Debug(this->jobId, this->taskId, this->requeueCount, "{0}, stream ? {1}", stdOutFile, this->streamOutput);
2015-04-24 07:32:37 +03:00
}
Process::~Process()
{
Logger::Debug(this->jobId, this->taskId, this->requeueCount, "~Process");
2015-04-24 07:32:37 +03:00
this->Kill();
2015-05-14 15:18:59 +03:00
pthread_rwlock_destroy(&this->lock);
2015-04-24 07:32:37 +03:00
}
2015-05-12 10:40:25 +03:00
void Process::Cleanup()
{
std::string output;
System::ExecuteCommandOut(output, "/bin/bash", "CleanupAllTasks.sh");
Logger::Info("Cleanup zombie result: {0}", output);
2015-04-24 07:32:37 +03:00
}
pplx::task<std::pair<pid_t, pthread_t>> Process::Start(std::shared_ptr<Process> self)
2015-04-24 07:32:37 +03:00
{
this->SetSelfPtr(self);
2015-04-24 07:32:37 +03:00
pthread_create(&this->threadId, nullptr, ForkThread, this);
Logger::Debug(this->jobId, this->taskId, this->requeueCount, "Created thread {0}", this->threadId);
2016-06-03 14:20:20 +03:00
return pplx::task<std::pair<pid_t, pthread_t>>(this->started);
2015-04-24 07:32:37 +03:00
}
void Process::Kill(int forcedExitCode, bool forced)
2015-03-30 17:40:36 +03:00
{
if (forcedExitCode != 0x0FFFFFFF)
{
Logger::Debug(this->jobId, this->taskId, this->requeueCount, "Setting forced ExitCode {0}", forcedExitCode);
2015-03-30 17:40:36 +03:00
this->SetExitCode(forcedExitCode);
}
2015-04-24 07:32:37 +03:00
if (!this->ended)
{
2017-08-03 11:27:32 +03:00
this->ExecuteCommand("/bin/bash", "EndTask.sh", this->taskExecutionId, this->processId, forced ? "1" : "0", this->taskFolder);
}
2015-03-30 17:40:36 +03:00
}
const ProcessStatistics& Process::GetStatisticsFromCGroup()
2015-03-30 17:40:36 +03:00
{
2015-05-05 10:35:29 +03:00
std::string stat;
2017-08-03 11:27:32 +03:00
System::ExecuteCommandOut(stat, "/bin/bash", "Statistics.sh", this->taskExecutionId, this->taskFolder);
2015-05-05 10:35:29 +03:00
Logger::Debug(this->jobId, this->taskId, this->requeueCount, "Statistics: {0}", stat);
2015-05-05 10:35:29 +03:00
std::istringstream statIn(stat);
WriterLock writerLock(&this->lock);
statIn >> this->statistics.UserTimeMs;
this->statistics.UserTimeMs *= 10;
2015-05-05 10:35:29 +03:00
statIn >> this->statistics.KernelTimeMs;
this->statistics.KernelTimeMs *= 10;
2015-05-05 10:35:29 +03:00
statIn >> this->statistics.WorkingSetKb;
Logger::Debug(this->jobId, this->taskId, this->requeueCount, "WorkingSet {0}", this->statistics.WorkingSetKb);
this->statistics.WorkingSetKb /= 1024;
2015-05-05 10:35:29 +03:00
this->statistics.ProcessIds.clear();
2015-05-05 10:35:29 +03:00
int id;
while (statIn >> id)
{
this->statistics.ProcessIds.push_back(id);
2015-05-05 10:35:29 +03:00
}
return this->statistics;
2015-04-24 07:32:37 +03:00
}
2016-06-07 22:54:56 +03:00
pplx::task<void> Process::OnCompleted()
{
return pplx::task<void>(this->completed);
}
void Process::OnCompletedInternal()
2015-04-24 07:32:37 +03:00
{
try
{
2016-06-13 00:05:02 +03:00
this->completed.set();
2015-05-05 10:35:29 +03:00
this->callback(
this->exitCode,
this->message.str(),
this->statistics);
2015-04-24 07:32:37 +03:00
}
catch (const std::exception& ex)
{
Logger::Error(this->jobId, this->taskId, this->requeueCount, "Exception happened when callback, ex = {0}", ex.what());
}
catch (...)
{
Logger::Error(this->jobId, this->taskId, this->requeueCount, "Unknown exception happened when callback");
}
}
void* Process::ForkThread(void* arg)
{
Process* const p = static_cast<Process* const>(arg);
std::string path;
2015-05-21 12:18:51 +03:00
Start:
2015-04-24 07:32:37 +03:00
int ret = p->CreateTaskFolder();
if (ret != 0)
{
p->message << "Task " << p->taskId << ": error when create task folder, ret " << ret << std::endl;
Logger::Error(p->jobId, p->taskId, p->requeueCount, "error when create task folder, ret {0}", ret);
2015-03-30 17:40:36 +03:00
p->SetExitCode(ret);
2015-04-24 07:32:37 +03:00
goto Final;
}
path = p->BuildScript();
if (path.empty())
2015-04-08 16:39:42 +03:00
{
2015-04-24 07:32:37 +03:00
p->message << "Error when build script." << std::endl;
Logger::Error(p->jobId, p->taskId, p->requeueCount, "Error when build script.");
p->SetExitCode((int)ErrorCodes::BuildScriptError);
goto Final;
}
2017-07-21 19:34:42 +03:00
if (!p->dockerImage.empty())
{
2017-09-26 12:22:24 +03:00
p -> environmentsBuffer.clear();
std::transform(
p->environments.cbegin(),
p->environments.cend(),
std::back_inserter(p->environmentsBuffer),
[](const auto& v) { return String::Join("=", v.first, v.second); });
2017-07-21 19:34:42 +03:00
std::string envFile = p->taskFolder + "/environments";
2017-09-26 12:22:24 +03:00
int ret = System::WriteStringToFile(envFile, String::Join<'\n'>(p->environmentsBuffer));
2017-09-18 16:34:04 +03:00
if (ret != 0)
2017-07-21 19:34:42 +03:00
{
2017-09-18 16:34:04 +03:00
Logger::Error(p->jobId, p->taskId, p->requeueCount, "Failed to create environment file for docker task. Exitcode: {0}", ret);
2017-07-21 19:34:42 +03:00
goto Final;
}
}
2017-08-03 11:27:32 +03:00
if (0 != p->ExecuteCommand("/bin/bash", "PrepareTask.sh", p->taskExecutionId, p->GetAffinity(), p->taskFolder, p->userName))
2015-04-24 07:32:37 +03:00
{
goto Final;
}
2015-05-18 06:29:06 +03:00
if (-1 == pipe(p->stdoutPipe))
2015-05-14 15:18:59 +03:00
{
2015-05-18 06:29:06 +03:00
p->message << "Error when create stdout pipe." << std::endl;
Logger::Error(p->jobId, p->taskId, p->requeueCount, "Error when create stdout pipe.");
2015-05-14 15:18:59 +03:00
2015-05-18 06:29:06 +03:00
p->SetExitCode(errno);
goto Final;
2015-05-14 15:18:59 +03:00
}
2015-04-24 07:32:37 +03:00
p->processId = fork();
if (p->processId < 0)
{
std::string errorMessage =
errno == EAGAIN ? "number of process reached upper limit" : "not enough memory";
p->message << "Failed to fork(), pid = " << p->processId << ", errno = " << errno
<< ", msg = " << errorMessage << std::endl;
Logger::Error(p->jobId, p->taskId, p->requeueCount, "Failed to fork(), pid = {0}, errno = {1}, msg = {2}", p->processId, errno, errorMessage);
p->SetExitCode(errno);
2016-06-03 14:20:20 +03:00
p->started.set(std::pair<pid_t, pthread_t>(p->processId, p->threadId));
2015-04-24 07:32:37 +03:00
goto Final;
}
if (p->processId == 0)
{
p->Run(path);
}
else
{
assert(p->processId > 0);
2016-06-03 14:20:20 +03:00
p->started.set(std::pair<pid_t, pthread_t>(p->processId, p->threadId));
2015-04-24 07:32:37 +03:00
p->Monitor();
}
Final:
2017-08-03 11:27:32 +03:00
p->ExecuteCommandNoCapture("/bin/bash", "EndTask.sh", p->taskExecutionId, p->processId, "1", p->taskFolder);
p->GetStatisticsFromCGroup();
2017-08-03 11:27:32 +03:00
ret = p->ExecuteCommandNoCapture("/bin/bash", "CleanupTask.sh", p->taskExecutionId, p->processId, p->taskFolder);
// Only clean up the folder when success.
if (p->exitCode == 0)
{
p->ExecuteCommandNoCapture("rm -rf", p->taskFolder);
}
if (p->outputThreadId != 0)
{
int joinret = pthread_join(p->outputThreadId, nullptr);
if (joinret != 0)
{
Logger::Error(p->jobId, p->taskId, p->requeueCount, "Join the output thread id {0}, ret = {1}", p->outputThreadId, joinret);
}
p->outputThreadId = 0;
}
2015-05-21 12:18:51 +03:00
// TODO: Add logic to precisely define 253 error.
if ((p->exitCode == 82 && ret == 96) || p->exitCode == 253)
2015-05-21 12:18:51 +03:00
{
p->exitCodeSet = false;
p->exitCode = (int)hpc::common::ErrorCodes::DefaultExitCode;
Logger::Error(p->jobId, p->taskId, p->requeueCount, "Exit Code {0} Reset exit code and retry to fork()", p->exitCode);
2015-05-21 12:18:51 +03:00
goto Start;
}
2015-04-24 07:32:37 +03:00
p->ended = true;
2015-05-18 06:29:06 +03:00
auto tmp = p->stdErr.str();
if (!tmp.empty()) { p->message << tmp; }
2016-06-07 22:54:56 +03:00
p->OnCompletedInternal();
p->ResetSelfPtr();
pthread_detach(pthread_self());
2015-04-24 07:32:37 +03:00
pthread_exit(nullptr);
}
2015-05-14 15:18:59 +03:00
void* Process::ReadPipeThread(void* p)
{
Logger::Info("Started reading pipe thread");
2015-05-18 06:29:06 +03:00
auto* process = static_cast<Process*>(p);
2015-05-14 15:18:59 +03:00
const std::string& uri = process->stdOutFile;
close(process->stdoutPipe[1]);
int bytesRead = 0;
char buffer[1024];
int order = 0;
while ((bytesRead = read(process->stdoutPipe[0], buffer, sizeof(buffer) - 1)) > 0)
{
buffer[bytesRead] = '\0';
auto readStr = String::Join("", buffer);
Logger::Debug("read {0} bytes, streamOutput {1}", bytesRead, process->streamOutput);
2015-05-18 06:29:06 +03:00
if (process->streamOutput)
{
// send out readStr
process->SendbackOutput(uri, readStr, order++);
}
else
{
process->stdErr << buffer;
}
2015-05-14 15:18:59 +03:00
}
Logger::Debug("read end. treamOutput {0}", process->streamOutput);
if (process->streamOutput)
{
process->SendbackOutput(uri, std::string(), order++);
}
2015-06-02 06:40:34 +03:00
2015-05-14 15:18:59 +03:00
close(process->stdoutPipe[0]);
pthread_exit(nullptr);
}
void Process::SendbackOutput(const std::string& uri, const std::string& output, int order) const
{
try
{
OutputData od(System::GetNodeName(), order, output);
2015-06-02 06:40:34 +03:00
if (output.empty()) { od.Eof = true; }
2015-05-14 15:18:59 +03:00
auto jsonBody = od.ToJson();
if (!jsonBody.is_null())
{
Logger::Debug(this->jobId, this->taskId, this->requeueCount,
"Callback to {0} with {1}", uri, jsonBody);
2017-03-29 18:19:03 +03:00
auto client = HttpHelper::GetHttpClient(uri);
auto request = HttpHelper::GetHttpRequest(methods::POST, jsonBody);
http_response response = client->request(*request).get();
2015-05-14 15:18:59 +03:00
Logger::Info(this->jobId, this->taskId, this->requeueCount,
"Callback to {0} response code {1}", uri, response.status_code());
}
}
catch (const std::exception& ex)
{
Logger::Error(this->jobId, this->taskId, this->requeueCount,
"Exception when sending back output. {0}", ex.what());
}
}
2015-04-24 07:32:37 +03:00
void Process::Monitor()
{
assert(this->processId > 0);
Logger::Debug(this->jobId, this->taskId, this->requeueCount, "Monitor the forked process {0}", this->processId);
2015-05-18 06:29:06 +03:00
pthread_create(&this->outputThreadId, nullptr, Process::ReadPipeThread, this);
2015-05-14 15:18:59 +03:00
2015-04-24 07:32:37 +03:00
int status;
rusage usage;
assert(this->processId > 0);
pid_t waitedPid = wait4(this->processId, &status, 0, &usage);
assert(this->processId > 0);
if (waitedPid == -1)
{
Logger::Error(this->jobId, this->taskId, this->requeueCount, "wait4 for process {0} error {1}", this->processId, errno);
this->message << "wait4 for process " << this->processId << " error " << errno << std::endl;
2015-03-30 17:40:36 +03:00
this->SetExitCode(errno);
2015-04-24 07:32:37 +03:00
return;
}
assert(this->processId > 0);
if (waitedPid != this->processId)
{
2015-04-08 16:39:42 +03:00
Logger::Error(this->jobId, this->taskId, this->requeueCount,
"Process {0}: waited {1}, errno {2}", this->processId, waitedPid, errno);
2015-04-24 07:32:37 +03:00
assert(false);
2015-03-30 17:40:36 +03:00
2015-04-24 07:32:37 +03:00
return;
}
if (WIFEXITED(status))
2015-03-30 17:40:36 +03:00
{
Logger::Info(this->jobId, this->taskId, this->requeueCount,
"Process {0}: exit code {1}", this->processId, WEXITSTATUS(status));
2015-03-30 17:40:36 +03:00
this->SetExitCode(WEXITSTATUS(status));
2015-05-14 15:18:59 +03:00
if (!this->streamOutput)
2015-04-24 07:32:37 +03:00
{
2015-05-14 15:18:59 +03:00
std::string output;
2017-09-11 12:39:42 +03:00
int ret = 0;
if (this->dumpStdout)
2015-05-14 15:18:59 +03:00
{
ret = System::ExecuteCommandOut(output, "head -c 1500", this->stdOutFile);
if (ret == 0)
{
this->message << "STDOUT: " << output << std::endl;
}
2015-05-14 15:18:59 +03:00
}
2015-04-24 07:32:37 +03:00
2015-05-18 06:29:06 +03:00
if (this->stdOutFile != this->stdErrFile)
2015-05-14 15:18:59 +03:00
{
2015-05-18 06:29:06 +03:00
ret = System::ExecuteCommandOut(output, "head -c 1500", this->stdErrFile);
if (ret == 0)
{
this->message << "STDERR: " << output << std::endl;
}
2015-05-14 15:18:59 +03:00
}
2015-04-24 07:32:37 +03:00
}
}
else
{
2015-04-23 15:18:33 +03:00
if (WIFSIGNALED(status))
{
Logger::Info(this->jobId, this->taskId, this->requeueCount, "Process {0}: WIFSIGNALED Signal {1}", this->processId, WTERMSIG(status));
2015-04-24 07:32:37 +03:00
this->message << "Process " << this->processId << ": WIFSIGNALED Signal " << WTERMSIG(status) << std::endl;
2015-04-23 15:18:33 +03:00
}
2015-04-24 07:32:37 +03:00
2015-04-23 15:18:33 +03:00
if (WCOREDUMP(status))
{
Logger::Info(this->jobId, this->taskId, this->requeueCount, "Process {0}: Core dumped.", this->processId);
2015-04-24 07:32:37 +03:00
this->message << "Process " << this->processId << ": Core dumped." << std::endl;
2015-04-23 15:18:33 +03:00
}
2015-04-24 07:32:37 +03:00
2015-04-23 15:18:33 +03:00
Logger::Error(this->jobId, this->taskId, this->requeueCount, "Process {0}: wait4 status {1}", this->processId, status);
2015-04-24 07:32:37 +03:00
this->SetExitCode(status);
this->message << "Process " << this->processId << ": wait4 status " << status << std::endl;
}
Logger::Debug(this->jobId, this->taskId, this->requeueCount, "Process {0}: Monitor ended", this->processId);
}
void Process::Run(const std::string& path)
{
2015-05-14 15:18:59 +03:00
if (this->streamOutput)
{
2015-05-18 06:29:06 +03:00
// in clusrun case, only monitor stdout, because stderr will be redirected
// to stdout
2015-05-14 15:18:59 +03:00
dup2(this->stdoutPipe[1], 1);
2015-05-18 06:29:06 +03:00
}
else
{
// in normal case, only monitor error messages from our own script
// customer script output will be redirected to the stdout/stderr file directly.
dup2(this->stdoutPipe[1], 2);
2015-05-14 15:18:59 +03:00
}
2015-05-18 06:29:06 +03:00
close(this->stdoutPipe[0]);
close(this->stdoutPipe[1]);
2015-04-24 07:32:37 +03:00
std::vector<char> pathBuffer(path.cbegin(), path.cend());
pathBuffer.push_back('\0');
char* const args[] =
{
const_cast<char* const>("/bin/bash"),
const_cast<char* const>("StartTask.sh"),
const_cast<char* const>(this->taskExecutionId.c_str()),
&pathBuffer[0],
const_cast<char* const>(this->userName.c_str()),
2017-08-03 11:27:32 +03:00
const_cast<char* const>(this->taskFolder.c_str()),
2015-04-24 07:32:37 +03:00
nullptr
};
auto envi = this->PrepareEnvironment();
int ret = execvpe(args[0], args, const_cast<char* const*>(envi.get()));
assert(ret == -1);
std::cout << "Error occurred when execvpe, errno = " << errno << std::endl;
exit(errno);
}
std::string Process::GetAffinity()
2015-04-23 13:35:14 +03:00
{
int cores, sockets;
System::CPU(cores, sockets);
std::string aff;
if (!this->affinity.empty())
{
std::ostringstream result;
for (int lastCore = 0, i = 0; i < cores; i++)
{
size_t affinityIndex = i / 64;
int affinityOffset = i % 64;
if (this->affinity.size() <= affinityIndex)
{
OutputAffinity(result, lastCore, i - 1);
break;
}
uint64_t currentAffinity = this->affinity[affinityIndex];
if (!((currentAffinity >> affinityOffset) << (63 - affinityOffset)))
{
// if the bit is not set;
OutputAffinity(result, lastCore, i - 1);
lastCore = i + 1;
}
else if (i == cores - 1)
{
OutputAffinity(result, lastCore, i);
}
}
aff = result.str();
}
if (aff.size() > 1)
{
return aff.substr(1);
}
else
{
return String::Join("-", "0", cores - 1);
}
2015-04-24 07:32:37 +03:00
}
int Process::CreateTaskFolder()
{
char folder[256];
sprintf(folder, "/tmp/nodemanager_task_%d_%d.XXXXXX", this->taskId, this->requeueCount);
2016-06-03 14:20:20 +03:00
int ret = System::CreateTempFolder(folder, this->userName);
2015-04-24 07:32:37 +03:00
2016-06-03 14:20:20 +03:00
if (ret != 0)
2015-04-24 07:32:37 +03:00
{
2016-06-03 14:20:20 +03:00
Logger::Debug(this->jobId, this->taskId, this->requeueCount, "CreateTaskFolder failed exitCode {0}.", ret);
}
2016-06-03 14:20:20 +03:00
this->taskFolder = folder;
2016-06-03 14:20:20 +03:00
return ret;
2015-04-24 07:32:37 +03:00
}
std::string Process::BuildScript()
{
std::string cmd = this->taskFolder + "/cmd.sh";
std::ofstream fsCmd(cmd, std::ios::trunc);
fsCmd << "#!/bin/bash" << std::endl << std::endl;
fsCmd << this->commandLine << std::endl;
2015-04-24 07:32:37 +03:00
fsCmd.close();
std::string runDirInOut = this->taskFolder + "/run_dir_in_out.sh";
std::ofstream fs(runDirInOut, std::ios::trunc);
fs << "#!/bin/bash" << std::endl << std::endl;
2017-09-11 12:39:42 +03:00
2016-06-03 14:20:20 +03:00
Logger::Debug("{0}, {1}", this->taskFolder, this->workDirectory);
2015-04-24 07:32:37 +03:00
2017-09-11 12:39:42 +03:00
std::string workDirectory = this->workDirectory.empty() ? this->taskFolder : this->workDirectory;
fs << "cd " << workDirectory << " || exit $?" << std::endl << std::endl;
2015-04-24 07:32:37 +03:00
2017-09-11 12:39:42 +03:00
if (this->stdOutFile.empty()) this->stdOutFile = this->taskFolder + "/stdout.txt";
else if (!boost::algorithm::starts_with(this->stdOutFile, "/") && !StartWithHttpOrHttps(this->stdOutFile)) this->stdOutFile = workDirectory + "/" + this->stdOutFile;
if (this->stdErrFile.empty()) this->stdErrFile = this->taskFolder + "/stderr.txt";
else if (!boost::algorithm::starts_with(this->stdErrFile, "/") && !StartWithHttpOrHttps(this->stdErrFile)) this->stdErrFile = workDirectory + "/" + this->stdErrFile;
2015-04-24 07:32:37 +03:00
// before
fs << "echo before >" << this->taskFolder << "/before1.txt 2>" << this->taskFolder << "/before2.txt";
fs << " || ([ \"$?\" = \"1\" ] && exit 253)" << std::endl;
// test
fs << "echo test >" << this->taskFolder << "/stdout.txt 2>" << this->taskFolder << "/stderr.txt";
fs << " || ([ \"$?\" = \"1\" ] && exit 253)" << std::endl << std::endl;
// run
2015-05-14 15:18:59 +03:00
if (this->streamOutput)
{
fs << "/bin/bash " << cmd << " 2>&1";
}
2015-05-18 06:29:06 +03:00
else if (this->stdOutFile == this->stdErrFile)
{
fs << "/bin/bash " << cmd << " >" << this->stdOutFile << " 2>&1";
}
2015-05-14 15:18:59 +03:00
else
{
2015-05-18 06:29:06 +03:00
fs << "/bin/bash " << cmd << " >" << this->stdOutFile << " 2>" << this->stdErrFile;
2015-05-14 15:18:59 +03:00
}
2015-04-24 07:32:37 +03:00
if (!this->stdInFile.empty())
{
fs << " <" << this->stdInFile;
}
fs << std::endl;
fs << "ec=$?" << std::endl;
fs << "[ $ec -ne 0 ] && exit $ec" << std::endl;
2015-04-24 07:32:37 +03:00
fs << std::endl << std::endl;
// after
fs << "echo after >" << this->taskFolder << "/after1.txt 2>" << this->taskFolder << "/after2.txt";
fs << " || ([ \"$?\" = \"1\" ] && exit 253)" << std::endl;
2015-04-24 07:32:37 +03:00
fs.close();
2017-09-26 12:22:24 +03:00
return std::move(runDirInOut);
2015-04-24 07:32:37 +03:00
}
std::unique_ptr<const char* []> Process::PrepareEnvironment()
{
this->environmentsBuffer.clear();
auto it = this->environments.find(std::string("PATH"));
if (it == this->environments.end())
{
char* currentPath = getenv("PATH");
this->environmentsBuffer.push_back(std::string("PATH=") + currentPath);
}
2015-04-24 07:32:37 +03:00
std::transform(
this->environments.cbegin(),
this->environments.cend(),
std::back_inserter(this->environmentsBuffer),
[](const auto& v) { return String::Join("=", v.first, v.second); });
auto envi = std::unique_ptr<const char* []>(new const char*[this->environments.size() + 1]);
int p = 0;
for_each(
this->environmentsBuffer.cbegin(),
this->environmentsBuffer.cend(),
[&p, &envi](const auto& i) { envi[p++] = i.c_str(); });
envi[p] = nullptr;
return std::move(envi);
}
std::string Process::PeekOutput()
{
2017-09-11 12:39:42 +03:00
std::string output;
int ret = 0;
std::string stdout;
2017-09-11 12:39:42 +03:00
ret = System::ExecuteCommandOut(stdout, "tail -c 5000 2>&1", this->stdOutFile);
if (ret != 0)
{
2017-09-26 12:22:24 +03:00
stdout = String::Join(" ", "Reading", this->stdOutFile, "failed with exitcode", ret, ":", stdout);
}
2017-09-11 12:39:42 +03:00
output = stdout;
2017-09-11 12:39:42 +03:00
if (this->stdOutFile != this->stdErrFile)
{
2017-09-11 12:39:42 +03:00
std::string stderr;
ret = System::ExecuteCommandOut(stderr, "tail -c 5000 2>&1", this->stdErrFile);
if (ret != 0)
{
2017-09-26 12:22:24 +03:00
stderr = String::Join(" ", "Reading", this->stdErrFile, "failed with exitcode", ret, ":", stderr);
2017-09-11 12:39:42 +03:00
}
output = String::Join("\n", "STDOUT:", stdout, "STDERR:", stderr);
}
2017-09-11 12:39:42 +03:00
return output;
}