/**
* Relational pipes
* Copyright © 2019 František Kučera (Frantovo.cz, GlobalCode.info)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <memory>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <locale>
#include <codecvt>
#include <regex>
#include <unistd.h>
#include <wait.h>
#include <ext/stdio_filebuf.h>
#include <relpipe/reader/typedefs.h>
#include <relpipe/reader/TypeId.h>
#include <relpipe/reader/handlers/RelationalReaderStringHandler.h>
#include <relpipe/reader/handlers/AttributeMetadata.h>
#include <relpipe/writer/Factory.h>
#include <relpipe/cli/RelpipeCLIException.h>
#include "Configuration.h"
namespace relpipe {
namespace tr {
namespace awk {
using namespace std;
using namespace relpipe;
using namespace relpipe::reader;
using namespace relpipe::reader::handlers;
/**
* This transformation consists of three processes connected together using pipes.
*
* Processes:
* - Parent: process RelationalReaderStringHandler events (read relational data, usually from STDIN) and pass them in the special text format to the pipe1
* - AWK: external program (/usr/bin/awk), read from the pipe1, writes to the pipe2
* - Writer: reads from the pipe2 and writes to relationalWriter (relational data, usually to STDOUT)
*/
class AwkHandler : public RelationalReaderStringHandler {
private:
Configuration configuration;
writer::RelationalWriter* relationalWriter;
std::wstring_convert<codecvt_utf8<wchar_t>> convertor; // TODO: support also other encodings
int awkInputWriterFD = -1;
std::vector<AttributeMetadata> currentReaderMetadata;
integer_t currentAttributeIndex = 0;
void createPipe(int& readerFD, int& writerFD) {
int fds[2];
int result = pipe(fds);
readerFD = fds[0];
writerFD = fds[1];
if (result < 0) throw cli::RelpipeCLIException(L"Unable to create a pipe.", cli::CLI::EXIT_CODE_UNEXPECTED_ERROR); // TODO: better exceptions?
}
void redirectFD(int oldfd, int newfd) {
int result = dup2(oldfd, newfd);
if (result < 0) throw cli::RelpipeCLIException(L"Unable redirect FD.", cli::CLI::EXIT_CODE_UNEXPECTED_ERROR); // TODO: better exceptions?
}
void closeOrThrow(int fd) {
int error = close(fd);
if (error) throw cli::RelpipeCLIException(L"Unable to close FD: " + to_wstring(fd) + L" from PID: " + to_wstring(getpid()), cli::CLI::EXIT_CODE_UNEXPECTED_ERROR); // TODO: better exceptions?
}
void execp(const std::vector<std::string>& args) {
const char** a = new const char*[args.size() + 1];
for (size_t i = 0; i < args.size(); i++) a[i] = args[i].c_str();
a[args.size()] = nullptr;
execvp(a[0], (char*const*) a);
delete[] a;
throw cli::RelpipeCLIException(L"Unable to do execvp().", cli::CLI::EXIT_CODE_UNEXPECTED_ERROR); // TODO: better exceptions?
}
void cleanUp() {
if (awkInputWriterFD >= 0) {
closeOrThrow(awkInputWriterFD);
// TODO: check exit codes
__pid_t waitResult1 = wait(NULL);
__pid_t waitResult2 = wait(NULL);
awkInputWriterFD = -1;
}
currentAttributeIndex = 0;
currentReaderMetadata.clear();
}
string_t a2v(const string_t& attributeName) {
// FIXME: escape reserved names; prefix with _ ?
// cat awkgram.y | awk -v FS='\\{"|",' -v ORS='|' '/static const struct token tokentab/, /\};/ { if (/^\{/) { print $2} }'
// BEGIN|BEGINFILE|END|ENDFILE|adump|and|asort|asorti|atan2|bindtextdomain|break|case|close|compl|continue|cos|dcgettext|dcngettext|default|delete|do|else|eval|exit|exp|fflush|for|func|function|gensub|getline|gsub|if|in|include|index|int|intdiv0|isarray|length|load|log|lshift|match|mktime|namespace|next|nextfile|or|patsplit|print|printf|rand|return|rshift|sin|split|sprintf|sqrt|srand|stopme|strftime|strtonum|sub|substr|switch|system|systime|tolower|toupper|typeof|while|xor
return attributeName;
}
string_t escapeAwkValue(const string_t& value) {
// FIXME: escape field and record separators
return value;
}
public:
AwkHandler(writer::RelationalWriter* relationalWriter, Configuration& configuration) : relationalWriter(relationalWriter), configuration(configuration) {
}
void startRelation(string_t name, vector<AttributeMetadata> attributes) override {
cleanUp();
currentReaderMetadata = attributes;
int awkInputReaderFD;
int awkOutputReaderFD;
int awkOutputWriterFD;
createPipe(awkInputReaderFD, awkInputWriterFD);
createPipe(awkOutputReaderFD, awkOutputWriterFD);
__pid_t awkPid = fork();
if (awkPid < 0) {
throw cli::RelpipeCLIException(L"Unable to fork AWK process.", cli::CLI::EXIT_CODE_UNEXPECTED_ERROR); // TODO: better exceptions?
} else if (awkPid == 0) {
// AWK child process
closeOrThrow(awkInputWriterFD);
closeOrThrow(awkOutputReaderFD);
redirectFD(awkInputReaderFD, STDIN_FILENO);
redirectFD(awkOutputWriterFD, STDOUT_FILENO);
std::wstringstream awkScript;
awkScript << L"BEGIN {" << std::endl;
awkScript << L"FS=\"\\t\";" << std::endl;
awkScript << L"};" << std::endl;
awkScript << L"END {" << std::endl;
// awkScript << … << std::endl;
awkScript << L"};" << std::endl;
awkScript << L"{print \"AWK says: line \" NR \" '\" $0 \"' has \" NF \" fields; first field is '\" $1 \"'\";}" << std::endl;
std::vector<std::string> args;
args.push_back("awk");
args.push_back(convertor.to_bytes(awkScript.str()));
// Runs AWK program found on $PATH → user can plug-in a custom implementation or a wrapper, but this can be also bit dangerous (however AWK itself is dangerous).
execp(args);
} else {
// Parent process
closeOrThrow(awkInputReaderFD);
closeOrThrow(awkOutputWriterFD);
__pid_t writerPid = fork();
if (writerPid < 0) {
throw cli::RelpipeCLIException(L"Unable to fork Writer process.", cli::CLI::EXIT_CODE_UNEXPECTED_ERROR); // TODO: better exceptions?
} else if (writerPid == 0) {
// Writer child process
closeOrThrow(awkInputWriterFD);
locale::global(locale("")); // needed for processing unicode texts, otherwise getline() stopped working on first line with non-ascii characters; TODO: move somewhere else?
__gnu_cxx::stdio_filebuf<wchar_t> awkOutputReaderBuffer(awkOutputReaderFD, std::ios::in);
std::wistream awkOutputReader(&awkOutputReaderBuffer);
relationalWriter->startRelation(L"writer_debug",{
{L"message", writer::TypeId::STRING},
}, true);
for (string_t line; getline(awkOutputReader, line).good();) {
relationalWriter->writeAttribute(line);
}
closeOrThrow(awkOutputReaderFD);
exit(0);
} else {
// Parent process
closeOrThrow(awkOutputReaderFD);
}
}
}
void attribute(const string_t& value) override {
string_t variableName = a2v(currentReaderMetadata[currentAttributeIndex].getAttributeName());
string_t variableValue = escapeAwkValue(value);
currentAttributeIndex++;
currentAttributeIndex = currentAttributeIndex % currentReaderMetadata.size();
// TODO: just the value – move name to the AWK function
std::string variablePair = convertor.to_bytes(variableName + L"=" + variableValue);
if (currentAttributeIndex == 0) variablePair += "\n";
else variablePair += "\t";
write(awkInputWriterFD, variablePair.c_str(), variablePair.length());
}
void endOfPipe() {
cleanUp();
}
};
}
}
}