├── example-gsgroups.conf ├── .gitmodules ├── example-gspasswd.conf ├── messages ├── en_US │ └── LC_MESSAGES │ │ ├── graphserv.mo │ │ └── graphserv.po └── graphserv.pot ├── .gitignore ├── proj ├── graphserv.workspace ├── graphserv-codelite │ ├── graphserv-codelite.workspace │ └── graphcore.project ├── graphserv.cbp └── graphserv_codelite.project ├── test ├── closetest │ ├── makefile │ └── closetest.cpp ├── rtest.sh └── concurrent.sh ├── README.rst ├── update-lang.sh ├── Makefile ├── src ├── servcli.h ├── const.h ├── utils.h ├── session.h ├── auth.h ├── coreinstance.h ├── main.cpp └── servapp.h ├── doc ├── install.rst └── usage.rst └── LICENSE /example-gsgroups.conf: -------------------------------------------------------------------------------- 1 | write:::melanie,jules,barney 2 | admin:::fred 3 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "graphcore"] 2 | path = graphcore 3 | url = git://github.com/wmde/graphcore.git 4 | -------------------------------------------------------------------------------- /example-gspasswd.conf: -------------------------------------------------------------------------------- 1 | melanie:R.NyWzK/TEEvo 2 | jules:G7eHdvAu5yibQ 3 | barney:e/CBifV4.zT.6 4 | fred:b.Bma5vYLxCwA 5 | -------------------------------------------------------------------------------- /messages/en_US/LC_MESSAGES/graphserv.mo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wmde/graphserv/master/messages/en_US/LC_MESSAGES/graphserv.mo -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.dat 2 | scite-session 3 | SciTE.properties 4 | *.list 5 | *.tags 6 | *.mk 7 | graphserv-codelite.workspace.* 8 | *.layout 9 | graphserv_codelite.sh 10 | graphserv 11 | graphserv.dbg 12 | *.log 13 | 14 | 15 | -------------------------------------------------------------------------------- /proj/graphserv.workspace: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /test/closetest/makefile: -------------------------------------------------------------------------------- 1 | closetest: closetest.cpp 2 | g++ closetest.cpp -o closetest 3 | 4 | 5 | # to be used on linux. 6 | # watch fds for connection being opened and closed. 7 | test: closetest 8 | -../../graphserv -g ../../example-gsgroups.conf -p ../../example-gspasswd.conf -c ../../graphcore/graphcore & echo $$! > PID 9 | sleep 0.5 10 | (echo "authorize password fred:test"; echo "create-graph test") | nc localhost 6666 11 | xterm -e watch -n 1 lsof -p $$(pidof graphserv) & sleep 1 12 | # spawn lots of instances 13 | for i in $$(seq 1 5000); do ./closetest 127.0.0.1 & done 14 | sleep 10 15 | kill $$(cat PID) 16 | rm PID 17 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Graph Processor server component - GraphServ 2 | ============================================ 3 | \(c) Wikimedia Deutschland, written by Johannes Kroll in 2011-2013 4 | 5 | For some information on using Graphserv/Graphcore for Wikipedia Tools -- what's currently running on Tool Labs, what can you do with it, how to use it -- see `this page `_. 6 | 7 | GraphServ Documentation: `install.rst `_, `usage.rst `_. 8 | 9 | Issue tracker: please file bugs and feature requests on `Phabricator `_. 10 | -------------------------------------------------------------------------------- /proj/graphserv-codelite/graphserv-codelite.workspace: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /update-lang.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # this script: 3 | # - updates the translation template file $MSGDIR/$DOMAIN.pot 4 | # - updates .po files with new translatable strings in source code 5 | # - compiles .po files to .mo files 6 | 7 | # directory where localization files are placed 8 | MSGDIR=messages 9 | 10 | # textdomain 11 | DOMAIN=graphserv 12 | 13 | # find languages 14 | LANGUAGES=$(cd $MSGDIR; find -mindepth 1 -maxdepth 1 -type d -execdir basename '{}' ';') 15 | 16 | SRC=$(find src -name '*.cpp'; find src -name '*.h') 17 | 18 | TMPPOT=$(mktemp) 19 | xgettext -d graphserv $SRC --keyword=_ -o - | sed "s/CHARSET/UTF-8/" > $TMPPOT && 20 | echo -n "merging new strings into template file $MSGDIR/$DOMAIN.pot " && 21 | msgmerge -U $MSGDIR/$DOMAIN.pot $TMPPOT && 22 | rm $TMPPOT && 23 | 24 | for LANG in $LANGUAGES; do 25 | echo -n "merging new strings into $LANG " && 26 | msgmerge -U $MSGDIR/$LANG/LC_MESSAGES/$DOMAIN.po $MSGDIR/$DOMAIN.pot && 27 | echo generating binary message catalog for $LANG && 28 | msgfmt -c -v -o $MSGDIR/$LANG/LC_MESSAGES/$DOMAIN.mo $MSGDIR/$LANG/LC_MESSAGES/$DOMAIN.po 29 | done 30 | 31 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # on solaris, we need -lsocket for socket functions. check for libsocket. 2 | ifneq ($(shell nm -DP /lib/libsocket.so* 2>/dev/null | grep -v UNDEF | grep '^accept[[:space:]]*'),) 3 | SOCKETLIB=-lsocket 4 | else 5 | SOCKETLIB= 6 | endif 7 | 8 | CCFLAGS=$(CFLAGS) -Wall -Wstrict-overflow=3 -std=c++0x -Igraphcore/src -DSYSTEMPAGESIZE=$(shell getconf PAGESIZE) 9 | LDFLAGS=-lcrypt $(SOCKETLIB) -levent 10 | 11 | all: Release Debug 12 | 13 | Release: graphserv 14 | Debug: graphserv.dbg 15 | 16 | graphcore/graphcore: graphcore/src/* 17 | +make -C graphcore STDERR_DEBUGGING=$(STDERR_DEBUGGING) USE_MMAP_POOL=$(USE_MMAP_POOL) DEBUG_COMMANDS=$(DEBUG_COMMANDS) Release 18 | 19 | graphcore/graphcore.dbg: graphcore/src/* 20 | +make -C graphcore STDERR_DEBUGGING=$(STDERR_DEBUGGING) USE_MMAP_POOL=$(USE_MMAP_POOL) DEBUG_COMMANDS=$(DEBUG_COMMANDS) Debug 21 | 22 | graphserv: src/main.cpp src/*.h graphcore/src/*.h graphcore/graphcore 23 | g++ $(CCFLAGS) -O3 -march=native src/main.cpp $(LDFLAGS) -ographserv 24 | 25 | graphserv.dbg: src/main.cpp src/*.h graphcore/src/*.h graphcore/graphcore.dbg 26 | g++ $(CCFLAGS) -DDEBUG_COMMANDS -ggdb src/main.cpp $(LDFLAGS) -ographserv.dbg 27 | 28 | # updatelang: update the language files 29 | # running this will generate changes in the repository 30 | updatelang: # 31 | ./update-lang.sh 32 | 33 | clean: # 34 | -rm graphserv graphserv.dbg graphcore/graphcore graphcore/graphcore.dbg 35 | 36 | # test: Release Debug 37 | # python test/talkback.py test/graphserv.tb ./graphserv 38 | 39 | .PHONY: updatelang clean 40 | -------------------------------------------------------------------------------- /test/closetest/closetest.cpp: -------------------------------------------------------------------------------- 1 | // quick test hack to check for leaked file descriptors. 2 | // running 'make test' on linux will spawn lots of graphserv connections using this program. 3 | // lsof should show all fds being closed. 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include /* for sockaddr_in and inet_addr() */ 11 | #include /* for memset() */ 12 | #include /* for close() */ 13 | 14 | void die(const char *str) 15 | { 16 | perror(str); 17 | exit(1); 18 | } 19 | 20 | int main(int argc, char **argv) 21 | { 22 | char *addrStr= (argc>1? argv[1]: (char*)"91.198.174.201"); 23 | int sock= socket(AF_INET, SOCK_STREAM, 0); 24 | if(sock==-1) die("socket"); 25 | sockaddr_in addr; 26 | memset(&addr, 0, sizeof(addr)); 27 | addr.sin_family= AF_INET; 28 | addr.sin_addr.s_addr= inet_addr(addrStr); 29 | addr.sin_port= htons(6666); 30 | if( connect(sock, (const struct sockaddr*)&addr, sizeof(sockaddr_in)) != 0 ) die("connect"); 31 | 32 | puts("connected."); 33 | const char *cmd= "use-graph test\n"; 34 | if( write(sock, cmd, strlen(cmd)) != strlen(cmd) ) die("write"); 35 | char buf[1024]; 36 | int r= read(sock, buf, sizeof(buf)); 37 | if(r==0) die("EOF"); 38 | if(r<0) die("read"); 39 | buf[r]= 0; 40 | printf("received: %s", buf); 41 | // sleep(3); 42 | puts("disconnecting."); 43 | close(sock); 44 | 45 | sleep(20); // keep the process alive for a while. 46 | 47 | return 0; 48 | } 49 | 50 | -------------------------------------------------------------------------------- /proj/graphserv.cbp: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 59 | 60 | -------------------------------------------------------------------------------- /src/servcli.h: -------------------------------------------------------------------------------- 1 | // Graph Processor server component. 2 | // (c) Wikimedia Deutschland, written by Johannes Kroll in 2011, 2012 3 | // server cli command base classes and cli handler class. 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | #ifndef SERVCLI_H 19 | #define SERVCLI_H 20 | 21 | // base class for server commands. 22 | class ServCmd: public CliCommand 23 | { 24 | public: 25 | virtual AccessLevel getAccessLevel() { return ACCESS_READ; } 26 | }; 27 | 28 | // cli commands which do not return any data. 29 | class ServCmd_RTVoid: public ServCmd 30 | { 31 | public: 32 | ReturnType getReturnType() { return RT_NONE; } 33 | virtual CommandStatus execute(vector words, class Graphserv &app, class SessionContext &sc)= 0; 34 | }; 35 | 36 | // cli commands which return some other data set. execute() must write the result to the client. 37 | class ServCmd_RTOther: public ServCmd 38 | { 39 | public: 40 | ReturnType getReturnType() { return RT_OTHER; } 41 | virtual CommandStatus execute(vector words, class Graphserv &app, class SessionContext &sc)= 0; 42 | }; 43 | 44 | // server cli class. 45 | class ServCli: public Cli 46 | { 47 | public: 48 | ServCli(class Graphserv &_app); 49 | 50 | void addCommand(ServCmd *cmd) 51 | { commands.push_back(cmd); } 52 | 53 | CommandStatus execute(string command, class SessionContext &sc); 54 | CommandStatus execute(class ServCmd *cmd, vector &words, class SessionContext &sc); 55 | 56 | private: 57 | class Graphserv &app; 58 | }; 59 | 60 | 61 | 62 | #endif // SERVCLI_H 63 | -------------------------------------------------------------------------------- /src/const.h: -------------------------------------------------------------------------------- 1 | // Graph Processor server component. 2 | // (c) Wikimedia Deutschland, written by Johannes Kroll in 2011, 2012 3 | // defines and constants used in the server. 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | #ifndef CONST_H 19 | #define CONST_H 20 | 21 | 22 | // default values for tcp & http listen ports 23 | #define DEFAULT_TCP_PORT 6666 24 | #define DEFAULT_HTTP_PORT 8090 25 | 26 | // listen backlog: how large may the queue of incoming connections grow 27 | #define LISTEN_BACKLOG 100 28 | 29 | // default filenames for htpasswd file, group file, and core binary 30 | #define DEFAULT_HTPASSWD_FILENAME "gspasswd.conf" 31 | #define DEFAULT_GROUP_FILENAME "gsgroups.conf" 32 | #define DEFAULT_CORE_PATH "./graphcore/graphcore" 33 | 34 | 35 | // the command status codes, including those used in the core. 36 | enum CommandStatus 37 | { 38 | CORECMDSTATUSCODES, 39 | // server-only status codes: 40 | CMD_ACCESSDENIED, // insufficient access level for command 41 | CMD_NOT_FOUND, // "command not found" results in a different HTTP status code, therefore it needs its own code. 42 | }; 43 | // NOTE: these entries must match the status codes above. 44 | static const string statusMsgs[]= 45 | { CORECMDSTATUSSTRINGS, DENIED_STR, FAIL_STR }; 46 | 47 | 48 | // the connection type of session contexts. 49 | enum ConnectionType 50 | { 51 | CONN_TCP= 0, 52 | CONN_HTTP 53 | }; 54 | 55 | 56 | // log levels for flog(). LOG_CRIT is always printed, other levels can be individually enabled on the command line. 57 | enum Loglevel 58 | { 59 | LOG_INFO, 60 | LOG_ERROR, 61 | LOG_AUTH, 62 | LOG_CRIT 63 | }; 64 | 65 | 66 | #endif // CONST_H 67 | -------------------------------------------------------------------------------- /test/rtest.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # server binary 4 | SERVBIN="../graphserv.dbg" 5 | # core binary. must use the debug version for list-by-* commands. 6 | COREBIN="../graphcore/graphcore.dbg" 7 | # use the example password and group files 8 | PWFILE="../example-gspasswd.conf" 9 | GRPFILE="../example-gsgroups.conf" 10 | # tcp port the server will listen on 11 | TCPPORT=6666 12 | 13 | HOST=nightshade.toolserver.org 14 | 15 | 16 | function random() { 17 | echo 'r = ' $RANDOM ' % 10000; scale=8; r * 0.0001 * ' $1 + $2 | bc 18 | } 19 | 20 | function add_arcs() { 21 | while true; do ( 22 | echo 'authorize password fred:test' 23 | echo 'use-graph test' 24 | local N=$(( $RANDOM % 5000 + 1 )) 25 | ( echo 'add-arcs:'; 26 | for k in $(seq 1 $N ) ; do 27 | echo "$(( $RANDOM % 1000 + 1)), $(( $RANDOM % 1000 + 1))"; 28 | done; echo "" ) ) | nc $HOST $TCPPORT >/dev/null || exit 0 29 | sleep $(random 1 .01) 30 | done 31 | } 32 | 33 | function remove_arcs() { 34 | while true; do 35 | N=$( (echo 'use-graph test'; echo 'stats'; sleep 2) | nc $HOST $TCPPORT | grep ArcCount | cut -d ',' -f 2 ) 36 | if [[ x$N == x ]]; then N=100; fi 37 | if (( $N > 50000 )); then 38 | N=$(( $N / 2 )) 39 | echo ' ***' removing $N 40 | (echo 'authorize password fred:test'; echo 'use-graph test'; 41 | echo "list-by-head 0 $N > tmpout") | nc $HOST $TCPPORT 42 | (echo 'authorize password fred:test'; 43 | echo 'use-graph test' 44 | echo 'remove-arcs < tmpout' 45 | echo stats 46 | sleep 10 47 | ) | nc $HOST $TCPPORT || exit 0 48 | #date +'%F %H:%M:%S' 49 | #echo '====== server: ======' 50 | #pmap $SERVPID | grep total 51 | #echo '====== core: ======' 52 | #pmap $COREPID | grep total 53 | fi 54 | sleep .5 #$(random .1 .1) 55 | done 56 | } 57 | 58 | 59 | function intcleanup() { 60 | echo ' SIGINT received, terminating server.' 61 | kill $SERVPID 62 | exit 0 63 | } 64 | 65 | 66 | if [[ $HOST == localhost ]]; then 67 | # start the server 68 | $SERVBIN -lia -p $TCPPORT -c $COREBIN -p $PWFILE -g $GRPFILE > graphserv.log 2>&1 & SERVPID=$! 69 | 70 | sleep .5 71 | 72 | # check if the server failed to start up. 73 | ps -p $SERVPID >/dev/null || exit 1 74 | 75 | COREPID=$( (echo 'authorize password fred:test'; echo 'create-graph test'; sleep 1) | nc localhost $TCPPORT | grep "spawned pid" | sed 's/^.*pid \([0-9]*\).*/\1/') 76 | 77 | echo core pid: $COREPID 78 | 79 | else 80 | 81 | (echo 'authorize password fred:test'; echo 'create-graph test'; sleep 1) | nc $HOST $TCPPORT 82 | 83 | fi 84 | 85 | trap intcleanup SIGINT 86 | 87 | add_arcs & 88 | remove_arcs & 89 | 90 | (while true; do sleep 10; done) 91 | 92 | 93 | -------------------------------------------------------------------------------- /doc/install.rst: -------------------------------------------------------------------------------- 1 | GraphServ: Installation 2 | ======================= 3 | 4 | The Graph Processor project aims to develop an infrastructure for rapidly analyzing and evaluating Wikipedia's category structure. The `GraphCore `_ component maintains and processes large directed graphs in memory. `GraphServ `_ handles access to running GraphCore instances. 5 | 6 | This file documents getting, building and running GraphServ. 7 | 8 | 9 | Getting the Code 10 | ---------------- 11 | 12 | Prerequisites: 13 | - `git `_ 14 | 15 | To clone a read-only copy of the GraphServ repository, use the following command: :: 16 | 17 | $ git clone --recursive git://github.com/jkroll20/graphserv.git 18 | 19 | The `--recursive` switch will automatically clone the required GraphCore repository as a submodule. 20 | 21 | 22 | 23 | Building 24 | -------- 25 | 26 | Prerequisites: 27 | - GNU Toolchain (make, g++, libc) 28 | - GNU `Readline `_. 29 | 30 | The build process does not involve the use of any autofrobnication scripts. To compile the code, simply run: :: 31 | 32 | $ make 33 | 34 | This will build debug and release binaries of GraphServ and GraphCore. 35 | 36 | The code should build and run on 32-Bit Linux and 64-Bit Solaris systems. Care was taken to ensure compatibility to other Unix-ish systems. If the code does not build or run on your platform, please let me know. 37 | 38 | 39 | Running GraphServ 40 | ----------------- 41 | 42 | By default, GraphServ will look for the GraphCore binary in the subdirectory `graphcore`. Default values for TCP ports and authentication files are also set at compile time. You may want to override these defaults using one of the command line options. :: 43 | 44 | use: graphserv [options] 45 | options: 46 | -h print this text 47 | -t PORT listen on PORT for tcp connections [6666] 48 | -H PORT listen on PORT for http connections [8090] 49 | -p FILENAME set htpassword file name [gspasswd.conf] 50 | -g FILENAME set group file name [gsgroups.conf] 51 | -c FILENAME set path of GraphCore binary [./graphcore/graphcore] 52 | -l FLAGS set logging flags. 53 | e: log error messages (default) 54 | i: log error and informational messages 55 | a: log authentication messages 56 | q: quiet mode, don't log anything 57 | flags can be combined. 58 | 59 | Before spawning a GraphCore instance, the child process will chdir() to the directory where graphcore resides. Currently, any redirected output will be written to that directory. Server log messages are written to stderr. 60 | 61 | 62 | | 63 | | 64 | | `GraphServ, GraphCore (C) 2011 Wikimedia Deutschland, written by Johannes Kroll .` 65 | | `Last update to this text: 2011/06/16` 66 | 67 | 68 | -------------------------------------------------------------------------------- /test/concurrent.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Graph Processor concurrency test script. 3 | # (c) Wikimedia Deutschland, written by Johannes Kroll in 2011 4 | 5 | # this script tests concurrent graph manipulation. 6 | # a number of random arcs are created ("input arcs"). 7 | # the input arcs are fed through graphcore, sorting them and removing duplicates ("comparison set"). 8 | # the input arcs are then split into several files. 9 | # each file is concurrently fed to a GraphCore instance, using several GraphServ sessions. 10 | # the result set from the core is then compared with the comparison set. 11 | # the test is successful if the result and comparison sets match. 12 | 13 | # the script will run $CONCURRENCY sessions at the same time, adding $ARCSPERPART random arcs each. 14 | CONCURRENCY=8 15 | ARCSPERPART=20000 16 | 17 | # server binary 18 | SERVBIN="../graphserv.dbg" 19 | # core binary. must use the debug version for list-by-* commands. 20 | COREBIN="../graphcore/graphcore.dbg" 21 | # use the example password and group files 22 | PWFILE="../example-gspasswd.conf" 23 | GRPFILE="../example-gsgroups.conf" 24 | # tcp port the server will listen on 25 | TCPPORT=6666 26 | 27 | NUMARCS=$(( $ARCSPERPART * $CONCURRENCY )) 28 | 29 | # build core & server 30 | echo "building..." 31 | (make -C.. Debug && make -C../graphcore Debug) >/dev/null 32 | if ! [[ -x $SERVBIN ]] || ! [[ -x $COREBIN ]] ; then echo 'Build failed.'; exit 1; fi 33 | 34 | # start the server 35 | $SERVBIN -lia -p $TCPPORT -c $COREBIN -p $PWFILE -g $GRPFILE & SERVPID=$! 36 | 37 | # creating random arcs should take long enough for the server to start up, don't sleep. 38 | #sleep 1 39 | 40 | echo "creating $NUMARCS random arcs..." 41 | 42 | # create some random arcs 43 | [ -f tmp-arcs ] && rm tmp-arcs 44 | i=0 45 | until [[ $i == $NUMARCS ]] ; do 46 | # $RANDOM is 0..32767. multiply to generate something between 0..ffffffff (not uniformly distributed) 47 | echo $(( $RANDOM * $RANDOM % ($NUMARCS/10) + 1 ))", "$(( $RANDOM * $RANDOM % ($NUMARCS/10) + 1 )) >> tmp-arcs 48 | let i++ 49 | done 50 | 51 | # sort them using graphcore 52 | (echo 'add-arcs < tmp-arcs'; echo 'list-by-tail 0') | $COREBIN | egrep -v '^$' | egrep -v '^OK' > tmp-arcs-sorted || exit 1 53 | # | grep -v "OK." | egrep -v "^$" 54 | 55 | # break them into pieces 56 | i=0 57 | part=0 58 | until [[ $i == $NUMARCS ]] ; do 59 | head -n $(( $i + $ARCSPERPART )) tmp-arcs | tail -n $ARCSPERPART > tmp-arcs-part$part 60 | let i+=$ARCSPERPART 61 | let part++ 62 | done 63 | 64 | # check if the server failed to start up. 65 | ps -p $SERVPID >/dev/null || exit 1 66 | 67 | # create test graph 68 | RESULT=$( 69 | ( echo 'authorize password fred:test' 70 | echo 'create-graph test' 71 | sleep 1 72 | ) | nc localhost $TCPPORT ) 73 | 74 | if ! [[ $RESULT =~ OK.*OK.* ]] ; then echo "couldn't create graph. output:"; echo "$RESULT"; kill $SERVPID; exit 1; fi 75 | 76 | # fill graph with the generated random data, concurrently, using several sessions 77 | PIDLIST="" 78 | part=0 79 | until [[ $part == $CONCURRENCY ]] ; do 80 | echo "starting part $part." 81 | >f$part 82 | ( 83 | (echo 'authorize password fred:test'; 84 | echo 'use-graph test'; 85 | echo 'add-arcs:'; cat tmp-arcs-part$part; echo ""; 86 | # make the process writing to netcat wait for the last "OK." output coming from netcat. 87 | # if we don't do this, netcat will finish early. 88 | while true; do if egrep "^OK\. $" f$part >/dev/null; then exit 0; fi; sleep 0.2; done 89 | sleep 1) \ 90 | | nc localhost $TCPPORT | tee f$part 91 | ) & PIDLIST="$PIDLIST $!" 92 | 93 | let part++ 94 | done 95 | 96 | # wait for all sessions to finish 97 | wait $PIDLIST 98 | 99 | # remove temporary files 100 | rm f? 101 | 102 | # now, get the result set stitched together from the concurrent sessions 103 | (echo "use-graph test"; 104 | echo "list-by-tail 0"; 105 | # wait for empty line. 106 | while true; do sleep 0.1; if tail -n 1 result-set | egrep "^$" >/dev/null; then exit 0; fi; done) | 107 | nc localhost $TCPPORT > result-set 108 | 109 | grep -v "OK." result-set | egrep -v '^$' > result-arcs 110 | 111 | echo "comparing result files with diff..." 112 | 113 | # compare result files 114 | 115 | if ! diff tmp-arcs-sorted result-arcs >/dev/null ; then 116 | echo "Test FAILED! Result files don't match." 117 | echo -n "sorted input arcs: "; sort tmp-arcs-sorted | uniq | wc -l 118 | echo -n " output arcs: "; uniq result-arcs | wc -l 119 | exit 1 120 | fi 121 | 122 | echo "Test SUCCEEDED. Result files match." 123 | 124 | rm tmp-arcs* result-set result-arcs* 125 | 126 | kill $SERVPID 127 | 128 | exit 0 129 | 130 | -------------------------------------------------------------------------------- /messages/graphserv.pot: -------------------------------------------------------------------------------- 1 | # Message template file for the graphserv program. 2 | # Copyright (C) Wikimedia Deutschland, created by Johannes Kroll in 2011 3 | # This file is distributed under the same license as the graphserv package. 4 | # Johannes Kroll , 2011. 5 | # 6 | #, fuzzy 7 | msgid "" 8 | msgstr "" 9 | "Project-Id-Version: graphserv\n" 10 | "Report-Msgid-Bugs-To: \n" 11 | "POT-Creation-Date: 2011-06-08 19:42+0200\n" 12 | "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" 13 | "Last-Translator: FULL NAME \n" 14 | "Language-Team: LANGUAGE \n" 15 | "Language: \n" 16 | "MIME-Version: 1.0\n" 17 | "Content-Type: text/plain; charset=UTF-8\n" 18 | "Content-Transfer-Encoding: 8bit\n" 19 | 20 | #: src/main.cpp:168 21 | msgid " no such server command.\n" 22 | msgstr "" 23 | 24 | #: src/main.cpp:179 src/servapp.h:325 25 | #, c-format 26 | msgid " insufficient access level (command needs %s, you have %s)\n" 27 | msgstr "" 28 | 29 | #: src/main.cpp:211 30 | msgid "create a named graphcore instance." 31 | msgstr "" 32 | 33 | #: src/main.cpp:222 34 | msgid "an instance with this name already exists.\n" 35 | msgstr "" 36 | 37 | #: src/main.cpp:224 38 | msgid "Graphserv::createCoreInstance() failed.\n" 39 | msgstr "" 40 | 41 | #: src/main.cpp:226 42 | #, c-format 43 | msgid "spawned pid %d.\n" 44 | msgstr "" 45 | 46 | #: src/main.cpp:237 47 | msgid "connect to a named graphcore instance." 48 | msgstr "" 49 | 50 | #: src/main.cpp:248 51 | msgid "already connected. switching instances is not currently supported.\n" 52 | msgstr "" 53 | 54 | #: src/main.cpp:250 src/main.cpp:274 55 | msgid "no such instance.\n" 56 | msgstr "" 57 | 58 | #: src/main.cpp:252 59 | #, c-format 60 | msgid "connected to pid %d.\n" 61 | msgstr "" 62 | 63 | #: src/main.cpp:263 64 | msgid "drop a named graphcore instance immediately (terminate the process)." 65 | msgstr "" 66 | 67 | #: src/main.cpp:277 68 | #, c-format 69 | msgid "couldn't kill the process. %s\n" 70 | msgstr "" 71 | 72 | #: src/main.cpp:280 73 | #, c-format 74 | msgid "killed pid %d.\n" 75 | msgstr "" 76 | 77 | #: src/main.cpp:292 78 | msgid "list currently running graphcore instances." 79 | msgstr "" 80 | 81 | #: src/main.cpp:303 82 | msgid "running graphs:\n" 83 | msgstr "" 84 | 85 | #: src/main.cpp:319 86 | msgid "returns information on your current session." 87 | msgstr "" 88 | 89 | #: src/main.cpp:330 90 | msgid "session info:\n" 91 | msgstr "" 92 | 93 | #: src/main.cpp:347 94 | msgid "returns information on the server." 95 | msgstr "" 96 | 97 | #: src/main.cpp:358 98 | msgid "server info:\n" 99 | msgstr "" 100 | 101 | #: src/main.cpp:373 102 | msgid "authorize with the named authority using the given credentials." 103 | msgstr "" 104 | 105 | #: src/main.cpp:388 106 | #, c-format 107 | msgid "no such authority '%s'.\n" 108 | msgstr "" 109 | 110 | #: src/main.cpp:394 111 | msgid "authorization failure.\n" 112 | msgstr "" 113 | 114 | #: src/main.cpp:398 115 | #, c-format 116 | msgid "access level: %s\n" 117 | msgstr "" 118 | 119 | #: src/main.cpp:411 120 | msgid "print info (debugging)" 121 | msgstr "" 122 | 123 | #: src/main.cpp:449 src/main.cpp:477 124 | msgid "get help on commands" 125 | msgstr "" 126 | 127 | #: src/main.cpp:457 src/main.cpp:496 128 | msgid "available commands:\n" 129 | msgstr "" 130 | 131 | #: src/main.cpp:462 132 | msgid "" 133 | "note: 'corehelp' prints help on core commands when connected to a core.\n" 134 | msgstr "" 135 | 136 | #: src/main.cpp:504 137 | msgid "the following are the core commands:\n" 138 | msgstr "" 139 | 140 | #: src/coreinstance.h:107 141 | msgid "core replied: " 142 | msgstr "" 143 | 144 | #: src/coreinstance.h:114 145 | msgid "protocol version mismatch (server: " 146 | msgstr "" 147 | 148 | #: src/coreinstance.h:126 149 | msgid "child process terminated by signal" 150 | msgstr "" 151 | 152 | #: src/coreinstance.h:130 153 | msgid "child process exited: " 154 | msgstr "" 155 | 156 | #: src/servapp.h:320 157 | #, c-format 158 | msgid "%s client has invalid core ID %u\n" 159 | msgstr "" 160 | 161 | #: src/servapp.h:330 162 | #, c-format 163 | msgid "no such core command '%s'." 164 | msgstr "" 165 | 166 | #: src/servapp.h:542 167 | #, c-format 168 | msgid "%s %s accepts no data set.\n" 169 | msgstr "" 170 | 171 | #: src/servapp.h:544 172 | msgid " input/output of server commands can't be redirected.\n" 173 | msgstr "" 174 | 175 | #: src/servapp.h:555 src/servapp.h:557 176 | #, c-format 177 | msgid "no such server command '%s'." 178 | msgstr "" 179 | 180 | #: src/servapp.h:572 181 | #, c-format 182 | msgid "bad HTTP request string, disconnecting.\n" 183 | msgstr "" 184 | 185 | #: src/servapp.h:579 186 | #, c-format 187 | msgid "unknown HTTP version, disconnecting.\n" 188 | msgstr "" 189 | 190 | #: src/servapp.h:599 191 | #, c-format 192 | msgid "i=%d len=%d %s %02X bad hex in request URI, disconnecting\n" 193 | msgstr "" 194 | 195 | #: src/servapp.h:607 196 | msgid " data sets not allowed in HTTP GET requests.\n" 197 | msgstr "" 198 | 199 | #: src/servapp.h:628 200 | msgid "No such instance." 201 | msgstr "" 202 | -------------------------------------------------------------------------------- /messages/en_US/LC_MESSAGES/graphserv.po: -------------------------------------------------------------------------------- 1 | # Message template file for the graphserv program. 2 | # Copyright (C) Wikimedia Deutschland, created by Johannes Kroll in 2011 3 | # This file is distributed under the same license as the graphserv package. 4 | # Johannes Kroll , 2011. 5 | # 6 | msgid "" 7 | msgstr "" 8 | "Project-Id-Version: graphserv\n" 9 | "Report-Msgid-Bugs-To: \n" 10 | "POT-Creation-Date: 2011-06-08 19:42+0200\n" 11 | "PO-Revision-Date: 2011-05-16 16:43+0100\n" 12 | "Last-Translator: Your name \n" 13 | "Language-Team: LANGUAGE \n" 14 | "Language: \n" 15 | "MIME-Version: 1.0\n" 16 | "Content-Type: text/plain; charset=UTF-8\n" 17 | "Content-Transfer-Encoding: 8bit\n" 18 | 19 | #: src/main.cpp:168 20 | msgid " no such server command.\n" 21 | msgstr "" 22 | 23 | #: src/main.cpp:179 src/servapp.h:325 24 | #, c-format 25 | msgid " insufficient access level (command needs %s, you have %s)\n" 26 | msgstr "" 27 | 28 | #: src/main.cpp:211 29 | msgid "create a named graphcore instance." 30 | msgstr "" 31 | 32 | #: src/main.cpp:222 33 | msgid "an instance with this name already exists.\n" 34 | msgstr "" 35 | 36 | #: src/main.cpp:224 37 | msgid "Graphserv::createCoreInstance() failed.\n" 38 | msgstr "" 39 | 40 | #: src/main.cpp:226 41 | #, c-format 42 | msgid "spawned pid %d.\n" 43 | msgstr "" 44 | 45 | #: src/main.cpp:237 46 | msgid "connect to a named graphcore instance." 47 | msgstr "" 48 | 49 | #: src/main.cpp:248 50 | msgid "already connected. switching instances is not currently supported.\n" 51 | msgstr "" 52 | 53 | #: src/main.cpp:250 src/main.cpp:274 54 | msgid "no such instance.\n" 55 | msgstr "" 56 | 57 | #: src/main.cpp:252 58 | #, c-format 59 | msgid "connected to pid %d.\n" 60 | msgstr "" 61 | 62 | #: src/main.cpp:263 63 | msgid "drop a named graphcore instance immediately (terminate the process)." 64 | msgstr "" 65 | 66 | #: src/main.cpp:277 67 | #, c-format 68 | msgid "couldn't kill the process. %s\n" 69 | msgstr "" 70 | 71 | #: src/main.cpp:280 72 | #, c-format 73 | msgid "killed pid %d.\n" 74 | msgstr "" 75 | 76 | #: src/main.cpp:292 77 | msgid "list currently running graphcore instances." 78 | msgstr "" 79 | 80 | #: src/main.cpp:303 81 | msgid "running graphs:\n" 82 | msgstr "" 83 | 84 | #: src/main.cpp:319 85 | msgid "returns information on your current session." 86 | msgstr "" 87 | 88 | #: src/main.cpp:330 89 | msgid "session info:\n" 90 | msgstr "" 91 | 92 | #: src/main.cpp:347 93 | msgid "returns information on the server." 94 | msgstr "" 95 | 96 | #: src/main.cpp:358 97 | msgid "server info:\n" 98 | msgstr "" 99 | 100 | #: src/main.cpp:373 101 | msgid "authorize with the named authority using the given credentials." 102 | msgstr "" 103 | 104 | #: src/main.cpp:388 105 | #, c-format 106 | msgid "no such authority '%s'.\n" 107 | msgstr "" 108 | 109 | #: src/main.cpp:394 110 | msgid "authorization failure.\n" 111 | msgstr "" 112 | 113 | #: src/main.cpp:398 114 | #, c-format 115 | msgid "access level: %s\n" 116 | msgstr "" 117 | 118 | #: src/main.cpp:411 119 | msgid "print info (debugging)" 120 | msgstr "" 121 | 122 | #: src/main.cpp:449 src/main.cpp:477 123 | msgid "get help on commands" 124 | msgstr "" 125 | 126 | #: src/main.cpp:457 src/main.cpp:496 127 | msgid "available commands:\n" 128 | msgstr "" 129 | 130 | #: src/main.cpp:462 131 | msgid "" 132 | "note: 'corehelp' prints help on core commands when connected to a core.\n" 133 | msgstr "" 134 | 135 | #: src/main.cpp:504 136 | msgid "the following are the core commands:\n" 137 | msgstr "" 138 | 139 | #: src/coreinstance.h:107 140 | msgid "core replied: " 141 | msgstr "" 142 | 143 | #: src/coreinstance.h:114 144 | msgid "protocol version mismatch (server: " 145 | msgstr "" 146 | 147 | #: src/coreinstance.h:126 148 | msgid "child process terminated by signal" 149 | msgstr "" 150 | 151 | #: src/coreinstance.h:130 152 | msgid "child process exited: " 153 | msgstr "" 154 | 155 | #: src/servapp.h:320 156 | #, c-format 157 | msgid "%s client has invalid core ID %u\n" 158 | msgstr "" 159 | 160 | #: src/servapp.h:330 161 | #, c-format 162 | msgid "no such core command '%s'." 163 | msgstr "" 164 | 165 | #: src/servapp.h:542 166 | #, c-format 167 | msgid "%s %s accepts no data set.\n" 168 | msgstr "" 169 | 170 | #: src/servapp.h:544 171 | msgid " input/output of server commands can't be redirected.\n" 172 | msgstr "" 173 | 174 | #: src/servapp.h:555 src/servapp.h:557 175 | #, c-format 176 | msgid "no such server command '%s'." 177 | msgstr "" 178 | 179 | #: src/servapp.h:572 180 | #, c-format 181 | msgid "bad HTTP request string, disconnecting.\n" 182 | msgstr "" 183 | 184 | #: src/servapp.h:579 185 | #, c-format 186 | msgid "unknown HTTP version, disconnecting.\n" 187 | msgstr "" 188 | 189 | #: src/servapp.h:599 190 | #, c-format 191 | msgid "i=%d len=%d %s %02X bad hex in request URI, disconnecting\n" 192 | msgstr "" 193 | 194 | #: src/servapp.h:607 195 | msgid " data sets not allowed in HTTP GET requests.\n" 196 | msgstr "" 197 | 198 | #: src/servapp.h:628 199 | msgid "No such instance." 200 | msgstr "" 201 | -------------------------------------------------------------------------------- /proj/graphserv-codelite/graphcore.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | make clean; make Debug 50 | make clean 51 | make Debug 52 | 53 | 54 | 55 | None 56 | /home/johannes/code/graphserv/graphcore 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | make clean; make Release 89 | make clean 90 | make STDERR_DEBUGGING=1 Release 91 | 92 | 93 | 94 | None 95 | ../.. 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | -------------------------------------------------------------------------------- /proj/graphserv_codelite.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | set follow-fork-mode child 47 | 48 | 49 | 50 | 51 | -killall graphserv.dbg 52 | 53 | 54 | make clean; make Debug 55 | make clean 56 | make STDERR_DEBUGGING=1 USE_MMAP_POOL=1 Debug 57 | 58 | 59 | 60 | None 61 | $(ProjectPath)/.. 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | set follow-fork-mode child 87 | 88 | 89 | 90 | 91 | -killall graphserv 92 | 93 | 94 | make clean; make 95 | make clean 96 | make STDERR_DEBUGGING=1 USE_MMAP_POOL=1 Release 97 | 98 | 99 | 100 | None 101 | $(ProjectPath)/.. 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /src/utils.h: -------------------------------------------------------------------------------- 1 | // Graph Processor server component. 2 | // (c) Wikimedia Deutschland, written by Johannes Kroll in 2011, 2012 3 | // utilities and helper functions. 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | #ifndef UTILS_H 19 | #define UTILS_H 20 | 21 | extern uint32_t logMask; 22 | 23 | void flog(Loglevel level, const char *fmt, ...) 24 | { 25 | if( !(logMask & (1<::iterator it= buffer.begin(); it!=buffer.end(); ++it) 158 | ret+= it->length(); 159 | return ret; 160 | } 161 | 162 | // error callback. 163 | virtual void writeFailed(int _errno)= 0; 164 | 165 | private: 166 | int fd; 167 | deque buffer; 168 | 169 | // write a string without buffering. return number of bytes written. 170 | size_t writeString(const string& s) 171 | { 172 | ssize_t sz= ::write(fd, s.data(), s.size()); 173 | if(sz<0) 174 | { 175 | if( (errno!=EAGAIN)&&(errno!=EWOULDBLOCK) ) 176 | logerror("write"), 177 | writeFailed(errno); 178 | return 0; 179 | } 180 | return sz; 181 | } 182 | }; 183 | 184 | #endif // UTILS_H 185 | -------------------------------------------------------------------------------- /src/session.h: -------------------------------------------------------------------------------- 1 | // Graph Processor server component. 2 | // (c) Wikimedia Deutschland, written by Johannes Kroll in 2011, 2012 3 | // session contexts. 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | #ifndef SESSION_H 19 | #define SESSION_H 20 | 21 | // session context with information about and methods for handling a client connection. 22 | // this base class handles TCP connections. 23 | struct SessionContext: public NonblockWriter 24 | { 25 | uint32_t clientID; 26 | AccessLevel accessLevel; 27 | ConnectionType connectionType; 28 | uint32_t coreID; // non-zero if connected to a core instance 29 | int sockfd; 30 | string linebuf; // text which is read from this client is buffered here. 31 | std::queue lineQueue; // lines which arrive from this client while the session is waiting for core reply are buffered here. 32 | class Graphserv &app; 33 | double chokeTime; 34 | // this is set when a client sends an invalid command with a data set. 35 | // the data set must be read and discarded. 36 | CommandStatus invalidDatasetStatus; 37 | string invalidDatasetMsg; // the status line to send after invalid data set has been read 38 | double shutdownTime; // time when shutdown was called on the socket, or 0 if the connection is running. 39 | 40 | CommandQEntry *curCommand; // if non-NULL, command which is currently being transferred to the server but not yet processed 41 | 42 | event *readEvent, *writeEvent; // libevent read and write events for sockfd 43 | int sockfdRead; // libevent doesn't support mixing edge- and level triggered events on the same fd, so 44 | // we need to dup() the socket fd for the read event... 45 | 46 | // some statistics about this connection. currently mostly used for debugging. 47 | struct Stats 48 | { 49 | double lastTime; 50 | union { struct { 51 | double linesSent, coreCommandsSent, servCommandsSent, 52 | bytesSent, dataRecordsSent, linesQueued; 53 | }; double values[6]; }; 54 | Stats() 55 | { reset(); } 56 | void reset(double t= getTime()) 57 | { 58 | lastTime= t; 59 | memset(values, 0, sizeof(values)); 60 | } 61 | void normalize(double t= getTime()) 62 | { 63 | double idt= 1.0/(t-lastTime); 64 | for(unsigned i= 0; i request; 127 | string requestString; 128 | unsigned commandsExecuted; 129 | HttpClientState(): commandsExecuted(0) { } 130 | } http; 131 | 132 | HTTPSessionContext(class Graphserv &app_, uint32_t cID, int sock): 133 | SessionContext(app_, cID, sock, CONN_HTTP), 134 | conversationFinished(false) 135 | { 136 | } 137 | 138 | void httpWriteResponseHeader(int code, const string &title, const string &contentType, const string &optionalField= "") 139 | { 140 | writef("HTTP/1.0 %d %s\r\n", code, title.c_str()); 141 | writef("Content-Type: %s\r\n", contentType.c_str()); 142 | if(optionalField.length()) 143 | { 144 | string field= optionalField; 145 | while(isspace(field[field.size()-1])) 146 | field.resize(field.size()-1); 147 | write(field); 148 | write("\r\n"); // make sure we have consistent newlines in the header. 149 | } 150 | writef("\r\n"); 151 | } 152 | 153 | void httpWriteErrorBody(const string& title, const string& description) 154 | { 155 | // writef("%s

%s

%s

\n", title.c_str(), title.c_str(), description.c_str()); 156 | // write(title + "\n" + description + "\n"); 157 | write(description); 158 | if(description.rfind('\n')!=description.size()-1) write("\n"); 159 | } 160 | 161 | void httpWriteErrorResponse(int code, const string &title, const string &description, const string &optionalField= "") 162 | { 163 | httpWriteResponseHeader(code, title, "text/plain", optionalField); 164 | httpWriteErrorBody(title, description); 165 | } 166 | 167 | // forward statusline to http client, possibly mark client to be disconnected 168 | void forwardStatusline(const string& line); 169 | 170 | // forward data set to http client, possibly mark client to be disconnected. 171 | void forwardDataset(const string& line) 172 | { 173 | write(line); 174 | if(Cli::splitString(line.c_str()).empty()) 175 | conversationFinished= true; // empty line marks end of data set, we're ready to disconnect. 176 | } 177 | 178 | virtual void commandNotFound(const string& text) 179 | { 180 | // special case: send http status code 501 instead of 400. 181 | httpWriteErrorResponse(501, "Not Implemented", string(FAIL_STR) + " " + text); 182 | conversationFinished= true; 183 | } 184 | }; 185 | 186 | 187 | 188 | #endif // SESSION_H 189 | -------------------------------------------------------------------------------- /doc/usage.rst: -------------------------------------------------------------------------------- 1 | GraphServ: Usage 2 | ================ 3 | 4 | The Graph Processor project aims to develop an infrastructure for rapidly analyzing and evaluating Wikipedia's category structure. The `GraphCore `_ component maintains and processes large directed graphs in memory. `GraphServ `_ handles access to running GraphCore instances. 5 | 6 | This file documents GraphServ usage. 7 | 8 | Users can connect to GraphServ via plaintext-TCP or HTTP. GraphServ multiplexes data to and from GraphServ instances and users. Several users can simultaneously execute commands on the same GraphServ instance, or on the same core. 9 | 10 | 11 | GraphServ Commands 12 | ------------------ 13 | 14 | GraphServ accepts commands and data in a line-based command language. Its command interface follows the same basic syntax and principles as is used for GraphCore commands (see `GraphCore spec `_). 15 | 16 | The following is the list of GraphServ commands. Words in square brackets denote access level (see below). 17 | 18 | create-graph [admin] :: 19 | 20 | create-graph GRAPHNAME 21 | create a named graphcore instance. 22 | graph names may contain only alphabetic characters (a-z A-Z), digits (0-9), hyphens (-) and underscores (_). 23 | graph names must start with an alphabetic character, a hyphen or an underscore. 24 | 25 | use-graph [read] :: 26 | 27 | use-graph GRAPHNAME 28 | connect to a named graphcore instance. 29 | 30 | authorize [read] :: 31 | 32 | authorize AUTHORITY CREDENTIALS 33 | authorize with the named authority using the given credentials. 34 | an authority named 'password' is implemented, which takes credentials of the form user:password. 35 | 36 | help [read] :: 37 | 38 | help [COMMAND] 39 | get help on server and core commands. 40 | 41 | drop-graph [admin] :: 42 | 43 | drop-graph GRAPHNAME 44 | drop a named graphcore instance immediately (terminate the process). 45 | 46 | list-graphs [read] :: 47 | 48 | list-graphs 49 | list currently running graphcore instances. 50 | 51 | session-info [read] :: 52 | 53 | session-info 54 | returns information on your current session. 55 | 56 | server-stats [read] :: 57 | 58 | server-stats 59 | returns information on the server. 60 | 61 | protocol-version [read] :: 62 | 63 | protocol-version 64 | the protocol-version is used to check for compatibility of the server and core binaries. 65 | this command prints the protocol-version of the server. 66 | 67 | 68 | Access Control 69 | -------------- 70 | 71 | Server and core commands are divided into three access levels: *read*, *write* and *admin*. To execute a command, a session's access level must be equal to or higher than the command's access level. 72 | 73 | GraphCore commands which modify a graph or its meta variables require *write* access. The *shutdown* command requires *admin* access. 74 | 75 | On connection, GraphServ assigns *read* access to a session. Access levels of a session can be elevated by using the *authorize* command, which tries to authorize with the given authority and credentials. 76 | 77 | Password Authority 78 | ++++++++++++++++++ 79 | 80 | The *password* authority implements access control using a htpassword-file and corresponding unix-style group file. A user authenticates by running the command *authorize password username:password*. 81 | 82 | The **htpassword file** contains entries of the form *user:password-hash* and can be created and modified with the `htpasswd `_ tool. GraphServ supports passwords hashed with crypt() (htpasswd -d). 83 | 84 | The **group file** contains entries of the form *access_level:password:GID:user_list*. The password and GID fields are ignored, and can be blank. *access_level* must be one of read, write, or admin. *user_list* is a comma-separated list of usernames. 85 | 86 | The password authority reads the contents of these files on demand. If one of the files is changed while the server is running, it will be reloaded once a user runs *authorize*. 87 | 88 | If a user name appears in more than one access level, the highest level will be used. 89 | 90 | Example htpasswd and group .conf files are included in the repository. All users in the example files use the password 'test'. 91 | 92 | 93 | TCP Connections 94 | --------------- 95 | 96 | Users can connect to GraphServ over TCP to execute commands. This example uses `netcat `_: :: 97 | 98 | $ nc localhost 6666 99 | help 100 | OK. available commands: 101 | # create-graph GRAPHNAME 102 | # use-graph GRAPHNAME 103 | # authorize AUTHORITY CREDENTIALS 104 | # help 105 | # drop-graph GRAPHNAME 106 | # list-graphs 107 | # session-info 108 | # server-stats 109 | 110 | 111 | 112 | 113 | HTTP Connections 114 | ---------------- 115 | 116 | GraphServ contains a rudimentary HTTP Server which implements a subset of `HTTP/1.0 `_. The HTTP Server accepts GET requests. One command can be executed per request. The server will close the connection after responding to the request. 117 | 118 | As a convenience, an HTTP/1.1 version string will also be accepted in GET requests. The version string in the GET request does not change the behaviour of the server or the contents of the response. 119 | 120 | In principle, an HTTP client can execute any core or server command. However, because the client is disconnected after executing the first command, an HTTP client can never execute a command which needs an access level above *read*. Also, HTTP clients cannot execute any command which takes a data set. These limitations could be removed in the future by implementing Keep-Alive connections (the default in HTTP/1.1), and/or POST. 121 | 122 | The request must follow the form *GET Request-URI Version-String CRLF
CRLF*. Any header fields following the Request-Line are read and discarded. 123 | 124 | The Request-URI can include `percent-encoded `_ characters. Any '+' characters in the Request-URI will be translated to space (0x20). 125 | 126 | 127 | Executing Server Commands 128 | +++++++++++++++++++++++++ 129 | 130 | To execute a server command, simply include the command string in the Request-URI. Example: :: 131 | 132 | $ curl http://localhost:8090/help # use curl to print help text of GraphServ on localhost listening on the default port. 133 | GET /help HTTP/1.0 # corresponding Request-Line. 134 | 135 | Executing Core Commands 136 | +++++++++++++++++++++++ 137 | 138 | To send a command to a core, include its name in the Request-URI. Separate core name and command by a forward slash. Example: :: 139 | 140 | $ curl http://localhost:8090/core0/list-predecessors+7 # print direct predecessors of node 7 in core0 on localhost. 141 | GET /core0/list-predecessors+7 HTTP/1.1 # corresponding Request-Line. 142 | 143 | HTTP Response and Status Code 144 | +++++++++++++++++++++++++++++ 145 | 146 | The HTTP server translates Graph Processor command status codes to HTTP Status-Codes in the following way: :: 147 | 148 | Success ('OK.') 200 OK 149 | Meta variable query succeeded ('VALUE:') 222 Value 150 | Failure, graph did not change ('FAILED!') 400 Bad Request 151 | Error, graph may have changed ('ERROR!') 500 Internal Server Error 152 | Success with empty result set ('NONE.') 404 Not Found 153 | Command not found (special case for HTTP) 501 Not Implemented 154 | Access Denied ('DENIED!') 401 Not Authorized 155 | 156 | Additionally, the untranslated status line is included in the *X-GraphProcessor:* header field of the HTTP response. 157 | 158 | The message-body of the response consists of the status line followed by any result data records or other command output. 159 | 160 | 161 | | 162 | | 163 | | `GraphServ, GraphCore (C) 2011, 2012 Wikimedia Deutschland, written by Johannes Kroll .` 164 | | `Last update to this text: 2012/01/05` 165 | 166 | 167 | -------------------------------------------------------------------------------- /src/auth.h: -------------------------------------------------------------------------------- 1 | // Graph Processor server component. 2 | // (c) Wikimedia Deutschland, written by Johannes Kroll in 2011, 2012 3 | // authority base class, password authority. 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | #ifndef AUTH_H 19 | #define AUTH_H 20 | 21 | 22 | enum AccessLevel 23 | { 24 | ACCESS_READ= 0, 25 | ACCESS_WRITE, 26 | ACCESS_ADMIN 27 | }; 28 | // these must match the access levels. 29 | static const char *gAccessLevelNames[]= 30 | { "read", "write", "admin" }; 31 | 32 | 33 | // abstract base class for authorities 34 | class Authority 35 | { 36 | public: 37 | Authority() { } 38 | virtual ~Authority() { } 39 | 40 | virtual string getName()= 0; 41 | // try to authorize using given credentials. write maximum access level to 'level' on success. 42 | virtual bool authorize(const string& credentials, AccessLevel &level)= 0; 43 | }; 44 | 45 | 46 | // the password authority reads from a htpasswd file and corresponding group file. 47 | // authorize() takes a string in the form "user:password". 48 | class PasswordAuth: public Authority 49 | { 50 | string htpasswdFilename; 51 | string groupFilename; 52 | 53 | struct userInfo 54 | { 55 | string hash; // the crypt()ed password 56 | AccessLevel accessLevel; // maximum access level 57 | }; 58 | map users; 59 | time_t lastCacheRefresh; 60 | 61 | vector splitLine(string line, char sep= ':') 62 | { 63 | string s; 64 | vector ret; 65 | if(line.empty()) return ret; 66 | while(isspace(line[line.size()-1])) line.resize(line.size()-1); 67 | line+= sep; 68 | for(size_t i= 0; i newUsers; 87 | // for each line in htpassword file 88 | while(fgets(line, 1024, f)) 89 | { 90 | // read line in the form user:hash and stuff it into the cache 91 | vector fields= splitLine(line); 92 | if(fields.size()==0) continue; 93 | if(fields.size()!=2 || fields[0].empty() || fields[1].size()!=13) 94 | { 95 | flog(LOG_ERROR, _("PasswordAuth: invalid line in htpasswd file\n")); 96 | fclose(f); 97 | return false; 98 | } 99 | userInfo ui= { fields[1], ACCESS_READ }; 100 | newUsers[fields[0]]= ui; 101 | } 102 | fclose(f); 103 | 104 | f= fopen(groupFilename.c_str(), "r"); 105 | if(!f) 106 | { 107 | flog(LOG_CRIT, _("couldn't open %s: %s\n"), groupFilename.c_str(), strerror(errno)); 108 | exit(1); 109 | } 110 | // for each line in group file 111 | while(fgets(line, 1024, f)) 112 | { 113 | // read line of the form accesslevel:::user1,user2,userX 114 | vector fields= splitLine(line); 115 | if(fields.size()==0) continue; 116 | if(fields.size()!=4 || fields[0].empty()) 117 | { 118 | flog(LOG_ERROR, _("PasswordAuth: invalid line in group file\n")); 119 | fclose(f); 120 | return false; 121 | } 122 | AccessLevel level; 123 | if(fields[0]==gAccessLevelNames[ACCESS_READ]) level= ACCESS_READ; 124 | else if(fields[0]==gAccessLevelNames[ACCESS_WRITE]) level= ACCESS_WRITE; 125 | else if(fields[0]==gAccessLevelNames[ACCESS_ADMIN]) level= ACCESS_ADMIN; 126 | else 127 | { 128 | flog(LOG_ERROR, _("PasswordAuth: invalid access level '%s' in group file\n"), fields[0].c_str()); 129 | fclose(f); 130 | return false; 131 | } 132 | 133 | // go through the specified users and elevate their access levels 134 | // so that each user gets the maximum specified: 135 | // a user in both "admin" and "write" groups gets admin access. 136 | vector usernames= splitLine(fields[3], ','); 137 | for(vector::iterator it= usernames.begin(); it!=usernames.end(); ++it) 138 | { 139 | map::iterator user= newUsers.find(*it); 140 | if(user!=newUsers.end() && level>user->second.accessLevel) 141 | user->second.accessLevel= level; 142 | } 143 | } 144 | 145 | // save cache only after we're successfully finished 146 | users.clear(); 147 | users= newUsers; 148 | fclose(f); 149 | return true; 150 | } 151 | 152 | void refreshFileCache() 153 | { 154 | time_t curtime= time(0); 155 | struct stat st; 156 | bool needRefresh= false; 157 | // check if any of the credential files have changed since last refresh. 158 | if(stat(htpasswdFilename.c_str(), &st)<0) 159 | { logerror(_("couldn't stat passwdfile")); return; } 160 | if(st.st_mtime>=lastCacheRefresh) needRefresh= true; 161 | else if(stat(groupFilename.c_str(), &st)<0) 162 | { logerror(_("couldn't stat groupfile")); return; } 163 | if(st.st_mtime>=lastCacheRefresh || needRefresh) 164 | { 165 | // something has changed, or we didn't read the files yet. 166 | // refresh the cache. 167 | lastCacheRefresh= curtime; 168 | readCredentialFiles(); 169 | } 170 | } 171 | 172 | public: 173 | PasswordAuth(const string& _htpasswdFilename, const string& _groupFilename): 174 | htpasswdFilename(_htpasswdFilename), groupFilename(_groupFilename), lastCacheRefresh(0) 175 | { 176 | readCredentialFiles(); 177 | lastCacheRefresh= time(0); 178 | } 179 | 180 | string getName() { return "password"; } 181 | 182 | bool authorize(const string& credentials, AccessLevel &level) 183 | { 184 | // load valid user/password combinations and group info into cache, if necessary. 185 | refreshFileCache(); 186 | 187 | vector cred= splitLine(credentials); 188 | if(cred.size()!=2 || cred[0].empty()||cred[1].empty()) 189 | { flog(LOG_AUTH, _("PasswordAuth: invalid credentials.\n")); return false; } 190 | 191 | map::iterator it= users.find(cred[0]); 192 | if(it==users.end()) 193 | { flog(LOG_AUTH, _("PasswordAuth: invalid user.\n")); return false; } 194 | 195 | // crypt() the password and compare to stored hash. 196 | char *crypted= crypt(cred[1].c_str(), it->second.hash.c_str()); 197 | if(crypted != it->second.hash) 198 | { 199 | flog(LOG_AUTH, _("PasswordAuth: failure, user %s\n"), it->first.c_str()); 200 | return false; 201 | } 202 | 203 | flog(LOG_AUTH, _("PasswordAuth: success, user %s, level %s\n"), it->first.c_str(), gAccessLevelNames[it->second.accessLevel]); 204 | 205 | level= it->second.accessLevel; 206 | 207 | return true; 208 | } 209 | }; 210 | 211 | 212 | #endif // AUTH_H 213 | -------------------------------------------------------------------------------- /src/coreinstance.h: -------------------------------------------------------------------------------- 1 | // Graph Processor server component. 2 | // (c) Wikimedia Deutschland, written by Johannes Kroll in 2011, 2012 3 | // CoreInstance class. handles graphcore command queueing and execution. 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | #ifndef COREINSTANCE_H 19 | #define COREINSTANCE_H 20 | 21 | // CoreInstance command queue entry. 22 | struct CommandQEntry 23 | { 24 | string command; // command 25 | deque dataset; // data set, if any 26 | uint32_t clientID; // who runs this command 27 | bool acceptsData; // command accepts an input data set (colon)? 28 | bool dataFinished; // data set was terminated with empty line? 29 | double sendBeginTime; // when did the client begin to send this command 30 | 31 | CommandQEntry(): clientID(0), acceptsData(false), dataFinished(true) 32 | { } 33 | 34 | CommandQEntry(uint32_t clientID_, string command_): command(command_), clientID(clientID_), acceptsData(false), dataFinished(true) 35 | { 36 | sendBeginTime= getTime(); 37 | if(lineIndicatesDataset(command)) 38 | acceptsData= true, 39 | dataFinished= false; 40 | } 41 | 42 | bool flushable() 43 | { 44 | return (!acceptsData) || dataFinished; 45 | } 46 | 47 | void appendToDataset(const string& line) 48 | { 49 | if(!acceptsData || dataFinished) 50 | return; 51 | dataset.push_back(line); 52 | if(Cli::splitString(line.c_str()).size()==0) 53 | dataFinished= true; 54 | } 55 | }; 56 | 57 | class LineRecvQ 58 | { 59 | public: 60 | deque nextLines(const string& str) 61 | { 62 | deque lineQueue; 63 | for(string::const_iterator it= str.begin(); it!=str.end(); ++it) 64 | { 65 | readbuf+= *it; 66 | if(*it=='\n') 67 | { 68 | lineQueue.push_back(readbuf); 69 | readbuf.clear(); 70 | } 71 | } 72 | return (lineQueue); 73 | } 74 | 75 | deque nextLines(int fd) 76 | { 77 | const size_t BUFSIZE= 1024; 78 | char buf[BUFSIZE]; 79 | ssize_t sz= read(fd, buf, sizeof(buf)-1); 80 | if(sz>0) 81 | { 82 | buf[sz]= 0; 83 | return (nextLines(buf)); 84 | } 85 | return (deque()); 86 | } 87 | private: 88 | string readbuf; 89 | }; 90 | 91 | // a CoreInstance object handles a GraphCore process. 92 | class CoreInstance: public NonblockWriter 93 | { 94 | public: 95 | string linebuf; // data read from core gets buffered here. 96 | LineRecvQ stderrQ; // data read from core stderr gets buffered here. 97 | 98 | CoreInstance(uint32_t _id, const string& _corePath): 99 | instanceID(_id), lastClientID(0), expectingReply(false), expectingDataset(false), corePath(_corePath), 100 | processRunning(false) 101 | { 102 | pipeToCore[0]= pipeToCore[1]= -1; 103 | pipeFromCore[0]= pipeFromCore[1]= -1; 104 | pipeFromCoreStderr[0]= pipeFromCoreStderr[1]= -1; 105 | } 106 | 107 | virtual ~CoreInstance() 108 | { 109 | close(pipeToCore[1]); 110 | close(pipeFromCore[0]); 111 | close(pipeFromCoreStderr[0]); 112 | } 113 | 114 | void writeFailed(int _errno) 115 | { 116 | logerror(_("write failed")); 117 | // read will return 0, core will be removed. 118 | } 119 | 120 | // try to start with given binary path name (default parameter falls back to the path set in constructor). 121 | bool startCore(const char *path= 0) 122 | { 123 | if(pipe(pipeToCore)==-1 || 124 | pipe(pipeFromCore)==-1 || 125 | pipe(pipeFromCoreStderr)==-1) 126 | { 127 | setLastError(string("pipe(): ") + strerror(errno)); 128 | return false; 129 | } 130 | 131 | if(path==0) path= corePath.c_str(); 132 | 133 | flog(LOG_INFO, _("starting core: %s\n"), path); 134 | 135 | // block sigint 136 | sigset_t mask, omask; 137 | sigemptyset(&mask); 138 | sigaddset(&mask, SIGINT); 139 | sigprocmask(SIG_BLOCK, &mask, &omask); 140 | 141 | // unblock sigint and change process group so that core doesn't receive graphserv's sigints 142 | // this has to be done in child+parent to avoid all possible race conditions 143 | auto sigintfoo= [&] (pid_t pid) 144 | { 145 | sigprocmask(SIG_SETMASK, &omask, NULL); 146 | setpgid(pid, pid); 147 | }; 148 | 149 | pid= fork(); 150 | if(pid==-1) 151 | { 152 | sigintfoo(pid); 153 | setLastError(string("fork(): ") + strerror(errno)); 154 | return false; 155 | } 156 | else if(pid==0) 157 | { 158 | // child process (core) 159 | sigintfoo(pid); 160 | 161 | if(dup2(pipeToCore[0], STDIN_FILENO)==-1 || 162 | dup2(pipeFromCore[1], STDOUT_FILENO)==-1 || 163 | dup2(pipeFromCoreStderr[1], STDERR_FILENO)==-1) 164 | exit(101); // setup failed 165 | 166 | close(pipeToCore[1]); 167 | close(pipeFromCore[0]); 168 | close(pipeFromCoreStderr[0]); 169 | 170 | setlinebuf(stdout); 171 | setlinebuf(stderr); 172 | 173 | // dirname and basename may modify their arguments, so duplicate the strings first. 174 | char dirnameBase[strlen(path)+1]; 175 | char basenameBase[strlen(path)+1]; 176 | strcpy(dirnameBase, path); 177 | strcpy(basenameBase, path); 178 | 179 | // change to the directory containing the binary 180 | if(chdir(dirname(dirnameBase))<0) 181 | exit(103); // couldn't chdir() 182 | 183 | char *binName= basename(basenameBase); 184 | if(execl(binName, format("%s-%s", binName, getName().c_str()).c_str(), NULL)<0) 185 | exit(102); // couldn't exec() 186 | } 187 | else 188 | { 189 | // parent process (server) 190 | sigintfoo(pid); 191 | 192 | close(pipeToCore[0]); 193 | close(pipeFromCore[1]); 194 | close(pipeFromCoreStderr[1]); 195 | 196 | FILE *toCore= fdopen(dup(pipeToCore[1]), "w"); 197 | FILE *fromCore= fdopen(dup(pipeFromCore[0]), "r"); 198 | 199 | setlinebuf(toCore); 200 | 201 | char line[1024]; 202 | 203 | // check that the protocol version strings match. 204 | fprintf(toCore, "protocol-version\n"); 205 | if(fgets(line, 1024, fromCore)) 206 | { 207 | chomp(line); 208 | // check that the protocol-version command succeeded. 209 | if(strncmp(SUCCESS_STR, line, strlen(SUCCESS_STR))!=0) 210 | { 211 | setLastError(_("core replied: ") + string(line)); 212 | fclose(toCore); fclose(fromCore); 213 | return false; 214 | } 215 | char *coreProtocolVersion= line + strlen(SUCCESS_STR); 216 | while(isspace(*coreProtocolVersion) && *coreProtocolVersion) coreProtocolVersion++; 217 | // check for matching version string. 218 | if(strcmp(coreProtocolVersion, stringify(PROTOCOL_VERSION))!=0) 219 | { 220 | setLastError(string(_("protocol version mismatch (server: ")) + 221 | stringify(PROTOCOL_VERSION) + " core: " + coreProtocolVersion + ")"); 222 | fclose(toCore); fclose(fromCore); 223 | return false; 224 | } 225 | setWriteFd(pipeToCore[1]); 226 | processRunning= true; 227 | fclose(toCore); fclose(fromCore); 228 | return true; 229 | } 230 | else // fgets() failed 231 | { 232 | int status; 233 | waitpid(pid, &status, 0); 234 | if(WIFSIGNALED(status)) 235 | setLastError(_("child process terminated by signal")); 236 | else if(WIFEXITED(status)) 237 | { 238 | int estatus= WEXITSTATUS(status); 239 | setLastError(string(_("child process exited: ")) + 240 | (estatus==101? _("setup failed."): 241 | estatus==102? string(_("couldn't exec '")) + path + "'.": 242 | estatus==103? string(_("couldn't change directory")): 243 | format(_("unknown error code %d"), estatus)) ); 244 | } 245 | else 246 | setLastError(_("child process terminated")); 247 | return false; 248 | } 249 | } 250 | return false; // never reached. make compiler happy. 251 | } 252 | 253 | string getLastError() { return lastError; } 254 | 255 | void setLastError(string str) { lastError= str; } 256 | 257 | uint32_t getID() { return instanceID; } 258 | string getName() { return (name.length()? name: format("Core%02u", instanceID)); } 259 | void setName(string nm) { name= nm; } // must *not* check for validity of name. 260 | pid_t getPid() { return pid; } 261 | int getReadFd() { return pipeFromCore[0]; } 262 | int getStderrReadFd() { return pipeFromCoreStderr[0]; } 263 | int getWriteFd() { return pipeToCore[1]; } 264 | 265 | // find *last* command for this client in queue 266 | CommandQEntry *findLastClientCommand(uint32_t clientID) 267 | { 268 | for(commandQ_t::reverse_iterator it= commandQ.rbegin(); it!=commandQ.rend(); ++it) 269 | if(it->clientID==clientID) 270 | return & (*it); 271 | return 0; 272 | } 273 | 274 | // try writing out commands from queue to core process 275 | void flushCommandQ(class Graphserv &app); 276 | 277 | // queue a command for execution. 278 | void queueCommand(string &cmd, uint32_t clientID, bool hasDataSet) 279 | { 280 | CommandQEntry ce; 281 | ce.acceptsData= hasDataSet; 282 | ce.dataFinished= false; 283 | ce.clientID= clientID; 284 | ce.command= cmd; 285 | ce.sendBeginTime= getTime(); 286 | commandQ.push_back(ce); 287 | } 288 | 289 | void queueCommand(CommandQEntry *ce) 290 | { 291 | commandQ.push_back(*ce); 292 | } 293 | 294 | // return the client which executed the last command; i. e. the client which current output from 295 | // core will be sent to. 296 | uint32_t getLastClientID() 297 | { 298 | return lastClientID; 299 | } 300 | 301 | // true if this core is running a command for this client or has a command for this client in its queue. 302 | bool hasDataForClient(uint32_t clientID) 303 | { 304 | // flog(LOG_INFO, "hasDataForClient: isclientid %d, expectingReply %d, expectingDataset %d, findLastClientCommand(clientID) %d\n", 305 | // lastClientID==clientID, expectingReply, expectingDataset, findLastClientCommand(clientID)); 306 | return (lastClientID==clientID && 307 | (expectingReply||expectingDataset)) 308 | || findLastClientCommand(clientID); 309 | } 310 | 311 | // handle a line of text which was sent from the core process. 312 | void lineFromCore(string &line, class Graphserv &app); 313 | 314 | // whether the process is running. false means it has not started yet or was terminated. 315 | bool isRunning() { return processRunning; } 316 | 317 | // terminate process. main loop will be notified of termination. 318 | bool terminate() 319 | { 320 | if(kill(pid, SIGTERM)<0) 321 | return false; 322 | processRunning= false; 323 | return true; 324 | } 325 | 326 | event *readEvent, *stderrReadEvent, *writeEvent; 327 | 328 | private: 329 | uint32_t instanceID; 330 | string lastError; 331 | string name; 332 | 333 | pid_t pid; 334 | int pipeToCore[2]; // writable from server (core's stdin) 335 | int pipeFromCore[2]; // writable from core (core's stdout) 336 | int pipeFromCoreStderr[2]; // writable from core (core's stderr) 337 | 338 | typedef deque commandQ_t; 339 | commandQ_t commandQ; 340 | 341 | uint32_t lastClientID; // ID of client who executed the last command. ie: client who should receive output 342 | 343 | bool expectingReply; // currently expecting a status reply from core (ok/failure/error) 344 | bool expectingDataset; // '' a data set from core 345 | 346 | string corePath; 347 | 348 | bool processRunning; 349 | 350 | friend class ccInfo; 351 | friend class ccShutdown; 352 | friend class ccCoreInfo; 353 | }; 354 | 355 | 356 | 357 | 358 | #endif // COREINSTANCE_H 359 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | // Graph Processor server component. 2 | // (c) Wikimedia Deutschland, written by Johannes Kroll in 2011, 2012 3 | // main module. 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | 48 | #include "clibase.h" 49 | #include "const.h" 50 | #include "utils.h" 51 | #include "auth.h" 52 | #include "coreinstance.h" 53 | #include "session.h" 54 | #include "servcli.h" 55 | #include "servapp.h" 56 | 57 | 58 | 59 | 60 | // GraphServ main module. 61 | // from the compiler's pov, all code is contained in one compilation unit, which creates 62 | // better opportunities for optimization and inlining. 63 | // member functions which can't be defined inside their class declarations are defined here. 64 | 65 | 66 | /////////////////////////////////////////// CoreInstance /////////////////////////////////////////// 67 | 68 | // handle a line of text arriving from a core. 69 | void CoreInstance::lineFromCore(string &line, class Graphserv &app) 70 | { 71 | SessionContext *sc= app.findClient(lastClientID); 72 | // check state and forward status line or data set to client. 73 | if(expectingReply) 74 | { 75 | expectingReply= false; 76 | if(lineIndicatesDataset(line)) 77 | expectingDataset= true; // save flag to determine when a command is finished. 78 | if(sc) 79 | { 80 | if(logMask&(1< words= Cli::splitString(line.c_str()); 83 | if(words.size() && getStatusCode(words[0])!=CMD_SUCCESS) 84 | flog(LOG_INFO, "core '%s', pid %d: status: %s", name.c_str(), pid, line.c_str()); 85 | } 86 | sc->forwardStatusline(line); // virtual fn does http-specific stuff 87 | } 88 | } 89 | else if(expectingDataset) 90 | { 91 | if(Cli::splitString(line.c_str()).size()==0) 92 | expectingDataset= false; // save flag to determine when a command is finished. 93 | if(sc) 94 | sc->forwardDataset(line); // virtual function does http-specific stuff, if any 95 | } 96 | else 97 | { 98 | // a core sent data we didn't ask for. this shouldn't happen. 99 | if(app.findClient(lastClientID)) 100 | flog(LOG_ERROR, _("CoreInstance '%s', ID %u: lineFromCore(): not expecting anything from this core\n"), getName().c_str(), getID()); 101 | } 102 | // write any pending commands to core process. 103 | flushCommandQ(app); 104 | } 105 | 106 | // write out as many commands from queue to core process as possible. 107 | void CoreInstance::flushCommandQ(class Graphserv &app) 108 | { 109 | while( commandQ.size() && (!expectingReply) && (!expectingDataset) && commandQ.front().flushable() ) 110 | { 111 | CommandQEntry &c= commandQ.front(); 112 | write(c.command); 113 | for(deque::iterator it= c.dataset.begin(); it!=c.dataset.end(); ++it) 114 | write(*it); 115 | lastClientID= c.clientID; 116 | expectingReply= true; 117 | expectingDataset= false; 118 | commandQ.pop_front(); 119 | } 120 | } 121 | 122 | 123 | 124 | 125 | /////////////////////////////////////////// SessionContext /////////////////////////////////////////// 126 | 127 | // error handler called because of broken connection or similar. tell app to disconnect this client. 128 | void SessionContext::writeFailed(int _errno) 129 | { 130 | flog(LOG_ERROR, _("client %d: write failed, disconnecting.\n"), clientID); 131 | app.forceClientDisconnect(this); 132 | } 133 | 134 | // true if this session is waiting for a reply from its connected core instance. 135 | bool SessionContext::isWaitingForCoreReply() 136 | { 137 | if(curCommand) return true; 138 | CoreInstance *instance= app.findInstance(coreID); 139 | if(!instance) return false; 140 | return instance->hasDataForClient(clientID); 141 | } 142 | 143 | // forward statusline to http client, possibly mark client to be disconnected 144 | void HTTPSessionContext::forwardStatusline(const string& line) 145 | { 146 | // if we already ran at least one command, don't write the HTTP header again. 147 | if(++http.commandsExecuted > 1) 148 | { 149 | SessionContext::forwardStatusline(line); 150 | return; 151 | } 152 | vector replyWords= Cli::splitString(line.c_str()); 153 | if(replyWords.empty()) 154 | { 155 | // this shouldn't happen. 156 | httpWriteErrorResponse(500, "Internal Server Error", _("Received empty status line from core. Please report.")); 157 | app.shutdownClient(this); 158 | } 159 | else 160 | { 161 | bool hasDataset= lineIndicatesDataset(line); 162 | string headerStatusLine= "X-GraphProcessor: " + line; 163 | 164 | switch(getStatusCode(replyWords[0])) 165 | { 166 | case CMD_SUCCESS: 167 | httpWriteResponseHeader(200, "OK", "text/plain", headerStatusLine); 168 | write(line); 169 | break; 170 | case CMD_FAILURE: 171 | httpWriteErrorResponse(400, "Bad Request", line, headerStatusLine); 172 | break; 173 | case CMD_ERROR: 174 | httpWriteErrorResponse(500, "Internal Server Error", line, headerStatusLine); 175 | break; 176 | case CMD_NONE: 177 | httpWriteErrorResponse(404, "Not Found", line, headerStatusLine); 178 | break; 179 | case CMD_ACCESSDENIED: 180 | httpWriteErrorResponse(401, "Not Authorized", line, headerStatusLine); 181 | break; 182 | case CMD_VALUE: 183 | httpWriteResponseHeader(222, "Value", "text/plain", headerStatusLine); 184 | write(line); 185 | break; 186 | default: 187 | httpWriteErrorResponse(500, "Invalid GraphCore Status Line", line, headerStatusLine); 188 | break; 189 | } 190 | 191 | // if there's nothing left to forward, mark client to be disconnected. 192 | if(!hasDataset) 193 | flog(LOG_INFO, _("client %d: conversation finished.\n"), clientID), 194 | conversationFinished= true; 195 | } 196 | } 197 | 198 | 199 | 200 | 201 | /////////////////////////////////////////// ServCli /////////////////////////////////////////// 202 | 203 | // parse and execute a server command line. 204 | CommandStatus ServCli::execute(string command, class SessionContext &sc) 205 | { 206 | vector words= splitString(command.c_str(), " \t\n"); 207 | if(words.empty()) return CMD_SUCCESS; 208 | ServCmd *cmd= (ServCmd*)findCommand(words[0]); 209 | if(!cmd) 210 | { 211 | sc.forwardStatusline(FAIL_STR + string(_(" no such server command.\n"))); 212 | return CMD_FAILURE; 213 | } 214 | return execute(cmd, words, sc); 215 | } 216 | 217 | // execute a server command. 218 | CommandStatus ServCli::execute(ServCmd *cmd, vector &words, SessionContext &sc) 219 | { 220 | if(cmd->getAccessLevel() > sc.accessLevel) 221 | { 222 | sc.forwardStatusline(DENIED_STR + format(_(" insufficient access level (command needs %s, you have %s)\n"), 223 | gAccessLevelNames[cmd->getAccessLevel()], gAccessLevelNames[sc.accessLevel])); 224 | return CMD_FAILURE; 225 | } 226 | CommandStatus ret; 227 | switch(cmd->getReturnType()) 228 | { 229 | case CliCommand::RT_OTHER: 230 | ret= ((ServCmd_RTOther*)cmd)->execute(words, app, sc); 231 | // ServCmd_RTOther::execute will forward everything to the client. 232 | break; 233 | case CliCommand::RT_NONE: 234 | ret= ((ServCmd_RTVoid*)cmd)->execute(words, app, sc); 235 | sc.forwardStatusline(cmd->getStatusMessage().c_str()); 236 | break; 237 | default: 238 | flog(LOG_ERROR, _("ServCli::execute: invalid return type %d\n"), cmd->getReturnType()); 239 | ret= CMD_ERROR; 240 | break; 241 | } 242 | return ret; 243 | } 244 | 245 | 246 | 247 | /////////////////////////////////////////// server commands /////////////////////////////////////////// 248 | 249 | class ccQuit: public ServCmd_RTOther 250 | { 251 | public: 252 | string getName() { return "quit"; } 253 | string getSynopsis() { return getName(); } 254 | string getHelpText() { return _("disconnect from the server."); } 255 | AccessLevel getAccessLevel() { return ACCESS_READ; } 256 | 257 | CommandStatus execute(vector words, class Graphserv &app, class SessionContext &sc) 258 | { 259 | if(words.size()!=1) 260 | { 261 | syntaxError(); 262 | return CMD_FAILURE; 263 | } 264 | cliSuccess("bye.\n"); 265 | sc.forwardStatusline(lastStatusMessage); 266 | app.shutdownClient(&sc); 267 | return CMD_SUCCESS; 268 | } 269 | 270 | }; 271 | 272 | class ccCreateGraph: public ServCmd_RTVoid 273 | { 274 | public: 275 | string getName() { return "create-graph"; } 276 | string getSynopsis() { return getName() + " GRAPHNAME"; } 277 | string getHelpText() { return _("create a named graphcore instance.\n" 278 | "# graph names may contain only alphabetic characters (a-z A-Z), digits (0-9), hyphens (-) and underscores (_).\n" 279 | "# graph names must start with an alphabetic character, a hyphen or an underscore."); } 280 | AccessLevel getAccessLevel() { return ACCESS_ADMIN; } 281 | 282 | CommandStatus execute(vector words, class Graphserv &app, class SessionContext &sc) 283 | { 284 | if(words.size()!=2) 285 | { 286 | syntaxError(); 287 | return CMD_FAILURE; 288 | } 289 | if(!app.isValidGraphName(words[1])) 290 | { 291 | cliFailure("invalid graph name.\n"); 292 | return CMD_FAILURE; 293 | } 294 | // check whether named instance already exists, try spawning core instance, return. 295 | if(app.findNamedInstance(words[1])) { cliFailure(_("an instance with this name already exists.\n")); return CMD_FAILURE; } 296 | CoreInstance *core= app.createCoreInstance(words[1]); 297 | if(!core) { cliFailure(_("Graphserv::createCoreInstance() failed.\n")); return CMD_FAILURE; } 298 | if(!core->startCore()) { cliFailure("startCore(): %s\n", core->getLastError().c_str()); return CMD_FAILURE; } 299 | app.addCoreInstance(core); 300 | cliSuccess(_("spawned pid %d.\n"), (int)core->getPid()); 301 | return CMD_SUCCESS; 302 | } 303 | 304 | }; 305 | 306 | class ccUseGraph: public ServCmd_RTVoid 307 | { 308 | public: 309 | string getName() { return "use-graph"; } 310 | string getSynopsis() { return getName() + " GRAPHNAME"; } 311 | string getHelpText() { return _("connect to a named graphcore instance."); } 312 | AccessLevel getAccessLevel() { return ACCESS_READ; } 313 | 314 | CommandStatus execute(vector words, class Graphserv &app, class SessionContext &sc) 315 | { 316 | if(words.size()!=2) 317 | { 318 | syntaxError(); 319 | return CMD_FAILURE; 320 | } 321 | 322 | CoreInstance *core= app.findNamedInstance(words[1]); 323 | if(!core) { cliFailure(_("no such instance.\n")); return CMD_FAILURE; } 324 | if(!app.reconnectSession(&sc, core)) 325 | { 326 | cliFailure(_("could not reconnect session.\n")); 327 | return CMD_FAILURE; 328 | } 329 | cliSuccess(_("connected to pid %d.\n"), (int)core->getPid()); 330 | return CMD_SUCCESS; 331 | } 332 | 333 | }; 334 | 335 | class ccDropGraph: public ServCmd_RTVoid 336 | { 337 | public: 338 | string getName() { return "drop-graph"; } 339 | string getSynopsis() { return getName() + " GRAPHNAME"; } 340 | string getHelpText() { return _("drop a named graphcore instance immediately (terminate the process)."); } 341 | AccessLevel getAccessLevel() { return ACCESS_ADMIN; } 342 | 343 | CommandStatus execute(vector words, class Graphserv &app, class SessionContext &sc) 344 | { 345 | if(words.size()!=2) 346 | { 347 | syntaxError(); 348 | return CMD_FAILURE; 349 | } 350 | CoreInstance *core= app.findNamedInstance(words[1]); 351 | if(!core) { cliNone(_("no such instance.\n")); return CMD_FAILURE; } 352 | if(!core->terminate()) 353 | { 354 | cliFailure(_("couldn't kill the process. %s\n"), strerror(errno)); 355 | return CMD_FAILURE; 356 | } 357 | flog(LOG_INFO, _("client %u killed core with ID %u, pid %d.\n"), sc.clientID, core->getID(), (int)core->getPid()); 358 | cliSuccess(_("killed core with ID %u, pid %d.\n"), core->getID(), (int)core->getPid()); 359 | // we shouldn't block here, waiting for the child is done in the select loop. 360 | // int status; 361 | // waitpid(core->getPid(), &status, 0); 362 | // app.removeCoreInstance(core); 363 | return CMD_SUCCESS; 364 | } 365 | 366 | }; 367 | 368 | class ccListGraphs: public ServCmd_RTOther 369 | { 370 | public: 371 | string getName() { return "list-graphs"; } 372 | string getSynopsis() { return getName(); } 373 | string getHelpText() { return _("list currently running graphcore instances."); } 374 | AccessLevel getAccessLevel() { return ACCESS_READ; } 375 | 376 | CommandStatus execute(vector words, class Graphserv &app, class SessionContext &sc) 377 | { 378 | if(words.size()!=1) 379 | { 380 | syntaxError(); 381 | sc.forwardStatusline(lastStatusMessage); 382 | return CMD_FAILURE; 383 | } 384 | cliSuccess(_("running graphs:\n")); 385 | sc.forwardStatusline(lastStatusMessage); 386 | map& cores= app.getCoreInstances(); 387 | for(map::iterator it= cores.begin(); it!=cores.end(); ++it) 388 | if(it->second->isRunning()) 389 | sc.forwardDataset(it->second->getName() + "\n"); 390 | sc.forwardDataset("\n"); 391 | return CMD_SUCCESS; 392 | } 393 | 394 | }; 395 | 396 | class ccSessionInfo: public ServCmd_RTOther 397 | { 398 | public: 399 | string getName() { return "session-info"; } 400 | string getSynopsis() { return getName() + " [GRAPH]"; } 401 | string getHelpText() { return _("returns information on your current session, or the session connected to GRAPH."); } 402 | AccessLevel getAccessLevel() { return ACCESS_READ; } 403 | 404 | CommandStatus execute(vector words, class Graphserv &app, class SessionContext &sc) 405 | { 406 | if(words.size()>2) 407 | { 408 | syntaxError(); 409 | sc.forwardStatusline(lastStatusMessage); 410 | return CMD_FAILURE; 411 | } 412 | SessionContext *sci= ≻ 413 | if(words.size()==2) 414 | { 415 | CoreInstance *ci= app.findNamedInstance(words[1]); 416 | if(!ci) 417 | { 418 | cliFailure(_("no such core '%s'\n"), words[1].c_str()); 419 | sc.forwardStatusline(lastStatusMessage); 420 | return CMD_FAILURE; 421 | } 422 | if(!(sci= app.findClientByCoreID(ci->getID()))) 423 | { 424 | cliFailure(_("core '%s' not connected to a client\n"), words[1].c_str()); 425 | sc.forwardStatusline(lastStatusMessage); 426 | return CMD_FAILURE; 427 | } 428 | } 429 | cliSuccess(_("session info:\n")); 430 | sc.forwardStatusline(lastStatusMessage); 431 | CoreInstance *ci= app.findInstance(sci->coreID); 432 | // prints minimal info. might print some session statistics (avg lines queued, etc). 433 | sc.forwardDataset(format("ConnectedGraph,%s\n", ci? ci->getName().c_str(): "None").c_str()); 434 | sc.forwardDataset(format("AccessLevel,%s\n", gAccessLevelNames[sci->accessLevel]).c_str()); 435 | sc.forwardDataset(format("dbg_linebuf_size,%d\n", sci->linebuf.size())); 436 | sc.forwardDataset(format("dbg_linequeue_size,%d\n", sci->lineQueue.size())); 437 | sc.forwardDataset(format("dbg_invalidDatasetStatus,%d\n", sci->invalidDatasetStatus)); 438 | sc.forwardDataset(format("dbg_shutdownTime,%.0f\n", sci->shutdownTime)); 439 | sc.forwardDataset("\n"); 440 | return CMD_SUCCESS; 441 | } 442 | 443 | }; 444 | 445 | class ccCoreInfo: public ServCmd_RTOther 446 | { 447 | public: 448 | string getName() { return "core-info"; } 449 | string getSynopsis() { return getName() + " GRAPH"; } 450 | string getHelpText() { return _("print debug information about GRAPH."); } 451 | AccessLevel getAccessLevel() { return ACCESS_READ; } 452 | 453 | CommandStatus execute(vector words, class Graphserv &app, class SessionContext &sc) 454 | { 455 | if(words.size()!=2) 456 | { 457 | syntaxError(); 458 | sc.forwardStatusline(lastStatusMessage); 459 | return CMD_FAILURE; 460 | } 461 | CoreInstance *ci= app.findNamedInstance(words[1]); 462 | if(!ci) 463 | { 464 | cliFailure(_("no such core '%s'\n"), words[1].c_str()); 465 | sc.forwardStatusline(lastStatusMessage); 466 | return CMD_FAILURE; 467 | } 468 | cliSuccess(_("core info:\n")); 469 | sc.forwardStatusline(lastStatusMessage); 470 | //~ sc.forwardDataset(format("ConnectedGraph,%s\n", ci? ci->getName().c_str(): "None").c_str()); 471 | //~ sc.forwardDataset(format("AccessLevel,%s\n", gAccessLevelNames[sci->accessLevel]).c_str()); 472 | //~ sc.forwardDataset(format("dbg_linebuf_size,%d\n", sci->linebuf.size())); 473 | //~ sc.forwardDataset(format("dbg_linequeue_size,%d\n", sci->lineQueue.size())); 474 | //~ sc.forwardDataset(format("dbg_invalidDatasetStatus,%d\n", sci->invalidDatasetStatus)); 475 | //~ sc.forwardDataset(format("dbg_shutdownTime,%.0f\n", sci->shutdownTime)); 476 | sc.forwardDataset(format("instanceID,%d\n", ci->instanceID)); 477 | sc.forwardDataset(format("commandQ.size__,%d\n", ci->commandQ.size())); 478 | sc.forwardDataset(format("commandQ.front__.flushable__,%s\n", ci->commandQ.front().flushable()? "true": "false")); 479 | sc.forwardDataset(format("expectingReply,%s\n", ci->expectingReply? "true": "false")); 480 | sc.forwardDataset(format("expectingDataset,%s\n", ci->expectingDataset? "true": "false")); 481 | sc.forwardDataset("\n"); 482 | return CMD_SUCCESS; 483 | } 484 | 485 | }; 486 | 487 | class ccServerStats: public ServCmd_RTOther 488 | { 489 | public: 490 | string getName() { return "server-stats"; } 491 | string getSynopsis() { return getName(); } 492 | string getHelpText() { return _("returns information on the server."); } 493 | AccessLevel getAccessLevel() { return ACCESS_READ; } 494 | 495 | CommandStatus execute(vector words, class Graphserv &app, class SessionContext &sc) 496 | { 497 | if(words.size()!=1) 498 | { 499 | syntaxError(); 500 | sc.forwardStatusline(lastStatusMessage); 501 | return CMD_FAILURE; 502 | } 503 | cliSuccess(_("server info:\n")); 504 | sc.forwardStatusline(lastStatusMessage); 505 | // this currently just outputs the minimal info: number of cores. should return more useful info. 506 | map& cores= app.getCoreInstances(); 507 | size_t runningCores= 0; 508 | for(map::iterator it= cores.begin(); it!=cores.end(); ++it) 509 | if(it->second->isRunning()) 510 | runningCores++; 511 | sc.forwardDataset(format("NCores,%zu\n", runningCores)); 512 | sc.forwardDataset(format("TotalLinesFromClients,%u\n", app.linesFromClients)); 513 | sc.forwardDataset("\n"); 514 | return CMD_SUCCESS; 515 | } 516 | 517 | }; 518 | 519 | class ccAuthorize: public ServCmd_RTVoid 520 | { 521 | public: 522 | string getName() { return "authorize"; } 523 | string getSynopsis() { return getName() + " AUTHORITY CREDENTIALS"; } 524 | string getHelpText() { return _("authorize with the named authority using the given credentials."); } 525 | AccessLevel getAccessLevel() { return ACCESS_READ; } 526 | 527 | CommandStatus execute(vector words, class Graphserv &app, class SessionContext &sc) 528 | { 529 | if(words.size()!=3) 530 | { 531 | syntaxError(); 532 | return CMD_FAILURE; 533 | } 534 | // find the authority to use. 535 | // currently there's only one (password). 536 | Authority *auth= app.findAuthority(words[1]); 537 | if(!auth) 538 | { 539 | cliFailure(_("no such authority '%s'.\n"), words[1].c_str()); 540 | return CMD_FAILURE; 541 | } 542 | AccessLevel newAccessLevel; 543 | if(!auth->authorize(words[2], newAccessLevel)) 544 | { 545 | cliFailure(_("authorization failure.\n")); 546 | return CMD_FAILURE; 547 | } 548 | sc.accessLevel= newAccessLevel; 549 | cliSuccess(_("access level: %s\n"), gAccessLevelNames[sc.accessLevel]); 550 | return CMD_SUCCESS; 551 | } 552 | 553 | }; 554 | 555 | class ccProtocolVersion: public ServCmd_RTVoid 556 | { 557 | public: 558 | string getName() { return "protocol-version"; } 559 | string getSynopsis() { return getName(); } 560 | string getHelpText() { return _("the protocol-version is used to check for compatibility of the server and core binaries.\n" 561 | "# this command prints the protocol-version of the server."); } 562 | AccessLevel getAccessLevel() { return ACCESS_READ; } 563 | 564 | CommandStatus execute(vector words, class Graphserv &app, class SessionContext &sc) 565 | { 566 | if(words.size()!=1) 567 | { 568 | syntaxError(); 569 | return CMD_FAILURE; 570 | } 571 | 572 | cliSuccess(stringify(PROTOCOL_VERSION) "\n"); 573 | 574 | return CMD_SUCCESS; 575 | } 576 | 577 | }; 578 | 579 | #ifdef DEBUG_COMMANDS 580 | // the "i" command is really just for debugging. 581 | class ccInfo: public ServCmd_RTOther 582 | { 583 | public: 584 | string getName() { return "i"; } 585 | string getSynopsis() { return getName(); } 586 | string getHelpText() { return _("print info (debugging)"); } 587 | AccessLevel getAccessLevel() { return ACCESS_READ; } 588 | 589 | CommandStatus execute(vector words, class Graphserv &app, class SessionContext &sc) 590 | { 591 | if(words.size()!=1) 592 | { 593 | syntaxError(); 594 | sc.forwardStatusline(lastStatusMessage); 595 | return CMD_FAILURE; 596 | } 597 | 598 | sc.writef("Cores: %d\n", app.coreInstances.size()); 599 | 600 | for(map::iterator it= app.coreInstances.begin(); it!=app.coreInstances.end(); ++it) 601 | { 602 | CoreInstance *ci= it->second; 603 | sc.writef("Core %d:\n", ci->getID()); 604 | sc.writef(" running: %s\n", ci->isRunning()? "true": "false"); 605 | sc.writef(" queue size: %u\n", ci->commandQ.size()); 606 | sc.writef(" bytes in write buffer: %u\n", ci->getWritebufferSize()); 607 | sc.writef(" expectingReply: %s\n", ci->expectingReply? "true": "false"); 608 | sc.writef(" expectingDataset: %s\n", ci->expectingDataset? "true": "false"); 609 | sc.writef("\n"); 610 | } 611 | 612 | for(map::iterator it= app.sessionContexts.begin(); it!=app.sessionContexts.end(); ++it) 613 | { 614 | SessionContext *ci= it->second; 615 | sc.writef("Session ID %d:\n", ci->clientID); 616 | sc.writef(" accessLevel: %s\n", gAccessLevelNames[ci->accessLevel]); 617 | sc.writef(" connectionType: %s\n", ci->connectionType==CONN_TCP? "TCP": "HTTP"); 618 | sc.writef(" coreID: %u\n", ci->coreID); 619 | sc.writef(" shutdownTime: %.2f (%.2f)\n", ci->shutdownTime, (ci->shutdownTime? getTime()-ci->shutdownTime: -1)); 620 | sc.writef("\n"); 621 | } 622 | 623 | return CMD_SUCCESS; 624 | } 625 | 626 | }; 627 | #endif 628 | 629 | // the alternative help command. "help" would be for the server help, "corehelp" for the core. 630 | // superseded by ccHelp below, which seems to work well. 631 | class ccHelpAlt: public ServCmd_RTOther 632 | { 633 | ServCli &cli; 634 | 635 | public: 636 | string getName() { return "help"; } 637 | string getSynopsis() { return getName(); } 638 | string getHelpText() { return _("get help on commands"); } 639 | AccessLevel getAccessLevel() { return ACCESS_READ; } 640 | 641 | ccHelpAlt(ServCli &_cli): cli(_cli) 642 | { } 643 | 644 | CommandStatus execute(vector words, Graphserv &app, SessionContext &sc) 645 | { 646 | cliSuccess(_("available commands:\n")); 647 | sc.forwardStatusline(lastStatusMessage); 648 | vector &commands= cli.getCommands(); 649 | for(size_t i= 0; igetSynopsis() + "\n"); 651 | sc.forwardDataset(string("# ") + _("note: 'corehelp' prints help on core commands when connected to a core.\n")); 652 | sc.forwardDataset("\n"); 653 | return CMD_SUCCESS; 654 | } 655 | 656 | }; 657 | 658 | // the help command for both server and core 659 | class ccHelp: public ServCmd_RTOther 660 | { 661 | ServCli &cli; 662 | 663 | public: 664 | string getName() { return "help"; } 665 | string getSynopsis() { return getName(); } 666 | string getHelpText() { return _("get help on commands"); } 667 | AccessLevel getAccessLevel() { return ACCESS_READ; } 668 | 669 | ccHelp(ServCli &_cli): cli(_cli) 670 | { } 671 | 672 | CommandStatus execute(vector words, Graphserv &app, SessionContext &sc) 673 | { 674 | if(words.size()>2) 675 | { 676 | syntaxError(); 677 | sc.forwardStatusline(lastStatusMessage); 678 | return CMD_FAILURE; 679 | } 680 | 681 | CoreInstance *ci= app.findInstance(sc.coreID); 682 | if(words.size()==1) 683 | { 684 | // show list of server commands 685 | cliSuccess(_("available server commands:\n")); 686 | sc.forwardStatusline(lastStatusMessage); 687 | vector &commands= (vector &)cli.getCommands(); 688 | for(size_t i= 0; igetSynopsis() + "\n"); 690 | if(ci) 691 | { 692 | // if connected, show list of core commands too. 693 | // sc.forwardDataset(string("# ") + _("the following are the core commands:\n")); 694 | string line; 695 | for(vector::iterator it= words.begin(); it!=words.end(); ++it) 696 | line+= *it, 697 | line+= " "; 698 | line+= "\n"; 699 | #ifndef NOSESSIONCONTEXTBUFFER 700 | app.forwardToCore(new CommandQEntry(sc.clientID, line), sc); 701 | #else 702 | app.sendCoreCommand(sc, line, false, &words); 703 | #endif 704 | } 705 | else sc.forwardDataset("\n"); 706 | } 707 | else 708 | { 709 | CliCommand *cmd= cli.findCommand(words[1]); 710 | if(cmd && cmd->getName()!="help") 711 | { 712 | // show help on server command 713 | cliSuccess("%s:\n", words[1].c_str()); 714 | sc.forwardStatusline(lastStatusMessage); 715 | sc.forwardDataset("# " + cmd->getSynopsis() + "\n" + 716 | "# " + cmd->getHelpText() + "\n\n"); 717 | } 718 | else if(app.findInstance(sc.coreID)) 719 | { 720 | // forward the command to the core 721 | string line; 722 | for(vector::iterator it= words.begin(); it!=words.end(); ++it) 723 | line+= *it, 724 | line+= " "; 725 | line+= "\n"; 726 | #ifndef NOSESSIONCONTEXTBUFFER 727 | app.forwardToCore(new CommandQEntry(sc.clientID, line), sc); 728 | #else 729 | app.sendCoreCommand(sc, line, false, &words); 730 | #endif 731 | } 732 | else 733 | { 734 | // no server command and not connected, forward error message. 735 | cliFailure(_("no such server command and not connected to a core instance.\n")); 736 | sc.forwardStatusline(lastStatusMessage); 737 | } 738 | } 739 | 740 | return CMD_SUCCESS; 741 | } 742 | 743 | }; 744 | 745 | 746 | // shutdown command is filtered by the server. 747 | class ccShutdown: public ServCmd_RTVoid 748 | { 749 | public: 750 | string getName() { return "shutdown"; } 751 | string getSynopsis() { return getName(); } 752 | string getHelpText() { return _("shut down the core instance you are connected to."); } 753 | AccessLevel getAccessLevel() { return ACCESS_ADMIN; } 754 | 755 | CommandStatus execute(vector words, class Graphserv &app, class SessionContext &sc) 756 | { 757 | if(words.size()!=1) 758 | { 759 | syntaxError(); 760 | return CMD_FAILURE; 761 | } 762 | 763 | CoreInstance *ci= app.findInstance(sc.coreID); 764 | if(!ci) 765 | { 766 | cliFailure(_("not connected to a core.\n")); 767 | return CMD_FAILURE; 768 | } 769 | 770 | flog(LOG_INFO, "sending shutdown command to core ID %u, pid %d, from client %u.\n", 771 | ci->getID(), (int)ci->getPid(), sc.clientID); 772 | 773 | // send the command to the core, mark the core as no longer running. 774 | // the client will still receive the reply from the core. 775 | #ifndef NOSESSIONCONTEXTBUFFER 776 | app.forwardToCore(new CommandQEntry(sc.clientID, "shutdown\n"), sc); 777 | #else 778 | app.sendCoreCommand(sc, "shutdown\n", false); 779 | #endif 780 | ci->processRunning= false; 781 | 782 | return CMD_SUCCESS; 783 | } 784 | }; 785 | 786 | 787 | 788 | 789 | ServCli::ServCli(Graphserv &_app): app(_app) 790 | { 791 | // register server commands. 792 | addCommand(new ccCreateGraph()); 793 | addCommand(new ccUseGraph()); 794 | #ifdef DEBUG_COMMANDS 795 | addCommand(new ccInfo()); 796 | addCommand(new ccCoreInfo()); 797 | #endif 798 | addCommand(new ccAuthorize()); 799 | addCommand(new ccHelp(*this)); 800 | addCommand(new ccDropGraph()); 801 | addCommand(new ccListGraphs()); 802 | addCommand(new ccSessionInfo()); 803 | addCommand(new ccServerStats()); 804 | addCommand(new ccProtocolVersion()); 805 | addCommand(new ccQuit()); 806 | addCommand(new ccShutdown()); 807 | } 808 | 809 | 810 | 811 | 812 | uint32_t logMask= (1<si_pid, si->si_status, si->si_signo, si->si_errno, si->si_code); 854 | } 855 | 856 | void handleSigchld() 857 | { 858 | static struct sigaction sa; 859 | sa.sa_sigaction= sigchldHandler; 860 | sa.sa_flags= SA_SIGINFO|SA_RESTART; 861 | sigaction(SIGCHLD, &sa, 0); 862 | } 863 | 864 | /////////////////////////////////////////// main /////////////////////////////////////////// 865 | 866 | int main(int argc, char *argv[]) 867 | { 868 | // default values can be overridden on the command line. 869 | int tcpPort= DEFAULT_TCP_PORT; 870 | int httpPort= DEFAULT_HTTP_PORT; 871 | string htpwFilename= DEFAULT_HTPASSWD_FILENAME; 872 | string groupFilename= DEFAULT_GROUP_FILENAME; 873 | string corePath= DEFAULT_CORE_PATH; 874 | bool useLibevent= false; 875 | 876 | // parse the command line. 877 | char opt; 878 | while( (opt= getopt(argc, argv, "ht:H:p:g:c:l:e"))!=-1 ) 879 | switch(opt) 880 | { 881 | case '?': 882 | printHelp(argv[0]); 883 | exit(1); 884 | case 'h': 885 | printHelp(argv[0]); 886 | exit(0); 887 | case 't': 888 | tcpPort= cmdlnParseUint(optarg); 889 | break; 890 | case 'H': 891 | httpPort= cmdlnParseUint(optarg); 892 | break; 893 | case 'p': 894 | htpwFilename= optarg; 895 | break; 896 | case 'g': 897 | groupFilename= optarg; 898 | break; 899 | case 'c': 900 | corePath= optarg; 901 | break; 902 | case 'l': 903 | for(int i= 0; optarg[i]; i++) switch(optarg[i]) 904 | { 905 | case 'i': 906 | logMask|= (1<. 17 | 18 | #ifndef SERVAPP_H 19 | #define SERVAPP_H 20 | 21 | // main application class. 22 | class Graphserv 23 | { 24 | public: 25 | Graphserv(int tcpPort_, int httpPort_, const string& htpwFilename, const string& groupFilename, const string& corePath_, bool useLibevent_): 26 | tcpPort(tcpPort_), httpPort(httpPort_), corePath(corePath_), useLibevent(useLibevent_), 27 | coreIDCounter(0), sessionIDCounter(0), 28 | cli(*this), linesFromClients(0), quit(false) 29 | { 30 | initCoreCommandTable(); 31 | 32 | Authority *auth= new PasswordAuth(htpwFilename, groupFilename); 33 | authorities.insert(pair (auth->getName(), auth)); 34 | } 35 | 36 | ~Graphserv() 37 | { 38 | for(auto it= authorities.begin(); it!=authorities.end(); ++it) 39 | delete it->second; 40 | authorities.clear(); 41 | 42 | for(auto it= coreInstances.begin(); it!=coreInstances.end(); ++it) 43 | delete it->second; 44 | coreInstances.clear(); 45 | 46 | for(auto it= sessionContexts.begin(); it!=sessionContexts.end(); ++it) 47 | delete it->second; 48 | sessionContexts.clear(); 49 | } 50 | 51 | Authority *findAuthority(const string& name) 52 | { 53 | map::iterator it= authorities.find(name); 54 | if(it!=authorities.end()) return it->second; 55 | return 0; 56 | } 57 | 58 | bool run() 59 | { 60 | listenSocket= (tcpPort? openListenSocket(tcpPort): 0); 61 | if(listenSocket<0) 62 | { 63 | flog(LOG_CRIT, _("couldn't create socket for TCP connections (port %d).\n"), tcpPort); 64 | return false; 65 | } 66 | httpSocket= (httpPort? openListenSocket(httpPort): 0); 67 | if(httpSocket<0) 68 | { 69 | flog(LOG_CRIT, _("couldn't create socket for HTTP connections (port %d).\n"), httpPort); 70 | return false; 71 | } 72 | 73 | struct rlimit rlim= { 0 }; 74 | getrlimit(RLIMIT_NOFILE, &rlim); 75 | flog(LOG_INFO, "RLIMIT_NOFILE: cur %ld, max %ld\n", long(rlim.rlim_cur), long(rlim.rlim_max)); 76 | 77 | handleSigint(); 78 | 79 | if(useLibevent) 80 | return mainloop_libevent(); 81 | else 82 | return mainloop_select(); 83 | } 84 | 85 | // check for valid graph name. 86 | // [a-zA-Z_-][a-zA-Z0-9_-]* 87 | bool isValidGraphName(const string& name) 88 | { 89 | int sz= name.size(); 90 | if(!sz) return false; 91 | char c= name[0]; 92 | if( !isupper(c) && !islower(c) && c!='-' && c!='_' ) return false; 93 | for(size_t i= 0; i::iterator it= coreInstances.begin(); it!=coreInstances.end(); ++it) 106 | if( it->second->getName()==name && (onlyRunning? it->second->isRunning(): true) ) 107 | return it->second; 108 | return 0; 109 | } 110 | 111 | // find an instance by ID (faster). 112 | CoreInstance *findInstance(uint32_t ID, bool onlyRunning= true) 113 | { 114 | map::iterator it= coreInstances.find(ID); 115 | if( it!=coreInstances.end() && (onlyRunning? it->second->isRunning(): true) ) return it->second; 116 | return 0; 117 | } 118 | 119 | // creates a new instance, without starting it or adding it to the event loop. 120 | CoreInstance *createCoreInstance(string name= "") 121 | { 122 | CoreInstance *inst= new CoreInstance(++coreIDCounter, corePath); 123 | inst->setName(name); 124 | return inst; 125 | } 126 | // add a core instance to the event loop. 127 | void addCoreInstance(CoreInstance *inst) 128 | { 129 | coreInstances.insert( pair(inst->getID(), inst) ); 130 | if(useLibevent) 131 | { 132 | flog(LOG_INFO, "setting up libevent stuff for core %s\n", inst->getName().c_str()); 133 | libeventData.cores[inst->getReadFd()]= inst; 134 | libeventData.cores[inst->getStderrReadFd()]= inst; 135 | libeventData.cores[inst->getWriteFd()]= inst; 136 | // read event forwarder for child's stdout and stderr handles 137 | auto read_cb= [] (evutil_socket_t fd, short what, void *arg) 138 | { 139 | ((Graphserv*)arg)->cb_coreReadable(fd, what); 140 | }; 141 | inst->readEvent= event_new(libeventData.base, inst->getReadFd(), EV_READ|EV_PERSIST, read_cb, this); 142 | inst->stderrReadEvent= event_new(libeventData.base, inst->getStderrReadFd(), EV_READ|EV_PERSIST, read_cb, this); 143 | inst->writeEvent= event_new(libeventData.base, inst->getWriteFd(), EV_WRITE|EV_PERSIST|EV_ET, [](evutil_socket_t fd, short what, void *arg) 144 | { 145 | ((Graphserv*)arg)->cb_coreWritable(fd, what); 146 | }, this); 147 | event_add(inst->readEvent, nullptr); 148 | event_add(inst->stderrReadEvent, nullptr); 149 | event_add(inst->writeEvent, nullptr); 150 | } 151 | } 152 | 153 | // removes a core instance from the list and deletes it 154 | void removeCoreInstance(CoreInstance *core) 155 | { 156 | map::iterator it= coreInstances.find(core->getID()); 157 | if(it!=coreInstances.end()) coreInstances.erase(it); 158 | if(useLibevent) 159 | { 160 | for(std::pair it: sessionContexts) 161 | { 162 | if(it.second->coreID==core->getID()) 163 | { 164 | flog(LOG_ERROR, _("removeCoreInstance(): removing client %d which is still connected to core '%s'\n"), it.second->clientID, core->getName().c_str()); 165 | shutdownClient(it.second); 166 | } 167 | } 168 | event_free(core->readEvent); 169 | event_free(core->stderrReadEvent); 170 | event_free(core->writeEvent); 171 | libeventData.cores.erase(core->getReadFd()); 172 | libeventData.cores.erase(core->getStderrReadFd()); 173 | libeventData.cores.erase(core->getWriteFd()); 174 | } 175 | delete core; 176 | } 177 | 178 | // find a session context (client). 179 | SessionContext *findClient(uint32_t ID) 180 | { 181 | set::iterator i= clientsToRemove.find(ID); 182 | if(i!=clientsToRemove.end()) return 0; 183 | map::iterator it= sessionContexts.find(ID); 184 | if(it!=sessionContexts.end()) return it->second; 185 | return 0; 186 | } 187 | 188 | // find a session context connected to a given core ID 189 | SessionContext *findClientByCoreID(uint32_t coreID) 190 | { 191 | for(auto &it: sessionContexts) 192 | if(it.second->coreID==coreID) 193 | return it.second; 194 | return 0; 195 | } 196 | 197 | // shut down the client socket. disconnect will happen in select loop when read returns zero. 198 | void shutdownClient(SessionContext *sc) 199 | { 200 | flog(LOG_INFO, "shutting down session %d.\n", sc->clientID); 201 | if(shutdown(sc->sockfd, SHUT_RDWR)<0) 202 | { 203 | logerror("shutdown"); 204 | forceClientDisconnect(sc); 205 | } 206 | sc->shutdownTime= getTime(); 207 | } 208 | 209 | // mark client connection to be forcefully broken. 210 | void forceClientDisconnect(SessionContext *sc) 211 | { 212 | if(clientsToRemove.find(sc->clientID)!=clientsToRemove.end()) 213 | return; 214 | clientsToRemove.insert(sc->clientID); 215 | } 216 | 217 | 218 | // get the core instances 219 | map& getCoreInstances() 220 | { 221 | return coreInstances; 222 | } 223 | 224 | // reconnect session to new core 225 | bool reconnectSession(SessionContext *sc, CoreInstance *core) 226 | { 227 | if(!sc || !core) return false; 228 | 229 | CoreInstance *oldCore= findInstance(sc->coreID); 230 | if(oldCore && oldCore->hasDataForClient(sc->clientID)) 231 | { 232 | // this is not fatal, but commands arriving from a different core could confuse client code. 233 | // to avoid this, clients should always wait for cores to reply before switching instances. 234 | flog(LOG_ERROR, _("old core instance %s still has data for client %d. " 235 | "client code should wait for core commands to finish before switching instances.\n"), 236 | oldCore->getName().c_str(), sc->clientID); 237 | } 238 | 239 | sc->coreID= core->getID(); 240 | return true; 241 | } 242 | private: 243 | int tcpPort, httpPort; 244 | string corePath; 245 | bool useLibevent; 246 | int listenSocket; 247 | int httpSocket; 248 | struct 249 | { 250 | struct event_base *base; 251 | // sockfd => SessionContext 252 | std::map sessions; 253 | // pipe fd => CoreInstance 254 | std::map cores; 255 | } libeventData; 256 | 257 | struct CoreCommandInfo 258 | { 259 | AccessLevel accessLevel; 260 | string coreImpDetail; 261 | }; 262 | map coreCommandInfos; 263 | 264 | uint32_t coreIDCounter; 265 | uint32_t sessionIDCounter; 266 | 267 | // core ID => instance 268 | map coreInstances; 269 | // session ID => context 270 | map sessionContexts; 271 | 272 | set clientsToRemove; 273 | 274 | ServCli cli; 275 | 276 | map authorities; 277 | 278 | uint32_t linesFromClients; 279 | 280 | bool quit; 281 | 282 | void handleSigint() 283 | { 284 | static auto sighandler= [this] (int signal, siginfo_t *si, void *context) -> void 285 | { 286 | static int ncalls= 0; 287 | if(ncalls==0) 288 | flog(LOG_CRIT, "hit ctrl-c again to quit\n"); 289 | else if(ncalls==1) 290 | flog(LOG_CRIT, "quitting\n"), 291 | this->quit= true; 292 | else 293 | flog(LOG_CRIT, "quitting morer\n"), 294 | exit(1); 295 | ++ncalls; 296 | }; 297 | static struct sigaction sa; 298 | sa.sa_flags= SA_SIGINFO|SA_RESTART; 299 | sa.sa_sigaction= [] (int signal, siginfo_t *si, void *context) -> void 300 | { 301 | sighandler(signal, si, context); 302 | }; 303 | sigaction(SIGINT, &sa, 0); 304 | } 305 | 306 | // create a reusable socket listening on the given port. 307 | int openListenSocket(int port) 308 | { 309 | int listenSocket= socket(AF_INET, SOCK_STREAM, 0); 310 | if(listenSocket==-1) { logerror("socket()"); return false; } 311 | 312 | // Allow socket descriptor to be reuseable 313 | int on= 1; 314 | int rc= setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)); 315 | if (rc < 0) 316 | { 317 | logerror("setsockopt() failed"); 318 | close(listenSocket); 319 | return -1; 320 | } 321 | 322 | struct sockaddr_in sa; 323 | memset(&sa, 0, sizeof(sa)); 324 | sa.sin_family= AF_INET; 325 | sa.sin_addr.s_addr= htonl(INADDR_ANY); 326 | sa.sin_port= htons(port); 327 | if(::bind(listenSocket, (sockaddr*)&sa, sizeof(sa))<0) 328 | { 329 | logerror("bind()"); 330 | close(listenSocket); 331 | return -1; 332 | } 333 | 334 | if(listen(listenSocket, LISTEN_BACKLOG)<0) 335 | { 336 | logerror("listen()"); 337 | close(listenSocket); 338 | return -1; 339 | } 340 | 341 | return listenSocket; 342 | } 343 | 344 | // helper function to add a file descriptor to an fd_set. 345 | void fd_add(fd_set &set, int fd, int &maxfd) 346 | { 347 | FD_SET(fd, &set); 348 | if(fd>maxfd) maxfd= fd; 349 | } 350 | 351 | // find information about a core command 352 | CoreCommandInfo *findCoreCommand(const string &name) 353 | { 354 | map::iterator it= coreCommandInfos.find(name); 355 | if(it!=coreCommandInfos.end()) return &it->second; 356 | return 0; 357 | } 358 | 359 | // initialize the core command info table. 360 | void initCoreCommandTable() 361 | { 362 | #define CORECOMMANDS_BEGIN 363 | #define CORECOMMANDS_END 364 | #define CORECOMMAND(name, level, imp...) ({ \ 365 | CoreCommandInfo cci= { level, #imp }; \ 366 | coreCommandInfos.insert( pair (name, cci) ); }) 367 | #include "corecommands.h" 368 | #undef CORECOMMANDS_BEGIN 369 | #undef CORECOMMANDS_END 370 | #undef CORECOMMAND 371 | } 372 | 373 | // accept connection on a socket and create session context. 374 | SessionContext *acceptConnection(int socket, ConnectionType type) 375 | { 376 | sockaddr sa; 377 | socklen_t addrlen= sizeof(sa); 378 | int newConnection= accept(socket, &sa, &addrlen); 379 | if(newConnection<0) 380 | { 381 | logerror("accept()"); 382 | return 0; 383 | } 384 | else 385 | { 386 | // add new connection 387 | //~ char addrstr[256]; 388 | //~ getnameinfo(&sa, addrlen, addrstr, sizeof(addrstr), NULL, 0, 0); 389 | flog(LOG_INFO, "new %s connection, socket=%d, %d connections active\n", (type==CONN_TCP? "TCP": "HTTP"), newConnection, sessionContexts.size()+1); 390 | return createSession(newConnection, type); 391 | } 392 | } 393 | 394 | // create a SessionContext or HTTPSessionContext, depending on connection type 395 | SessionContext *createSession(int sock, ConnectionType connType= CONN_TCP) 396 | { 397 | uint32_t newID= ++sessionIDCounter; 398 | if(!closeOnExec(sock)) return 0; 399 | SessionContext *newSession; 400 | switch(connType) 401 | { 402 | case CONN_TCP: newSession= new SessionContext(*this, newID, sock, connType); break; 403 | case CONN_HTTP: newSession= new HTTPSessionContext(*this, newID, sock); break; 404 | default: flog(LOG_ERROR, "createSession: unknown connection type %d!\n", connType); return 0; 405 | } 406 | sessionContexts.insert( pair(newID, newSession) ); 407 | return newSession; 408 | } 409 | 410 | // immediately remove a session. 411 | bool removeSession(uint32_t sessionID) 412 | { 413 | map::iterator it= sessionContexts.find(sessionID); 414 | if(it!=sessionContexts.end()) 415 | { 416 | flog(LOG_INFO, "removing client %d, %d sessions active\n", it->second->clientID, sessionContexts.size()-1); 417 | 418 | shutdown(it->second->sockfd, SHUT_RDWR); 419 | 420 | if(useLibevent) 421 | { 422 | event_free(it->second->readEvent); 423 | event_free(it->second->writeEvent); 424 | shutdown(it->second->sockfdRead, SHUT_RDWR); 425 | setNonblocking(it->second->sockfdRead, false); 426 | close(it->second->sockfdRead); 427 | libeventData.sessions.erase(it->second->sockfd); 428 | libeventData.sessions.erase(it->second->sockfdRead); 429 | } 430 | 431 | CoreInstance *ci; 432 | if( it->second->coreID && 433 | (ci= findInstance(it->second->coreID)) ) 434 | { 435 | CommandQEntry *cqe= ci->findLastClientCommand(it->second->clientID); 436 | if(cqe && cqe->acceptsData && (!cqe->dataFinished)) 437 | { 438 | flog(LOG_ERROR, _("terminating open data set of connected core '%s' (ID %u)\n"), ci->getName().c_str(), ci->getID()); 439 | cqe->appendToDataset("\n\n"); 440 | } 441 | } 442 | delete(it->second); 443 | sessionContexts.erase(it); 444 | return true; 445 | } 446 | return false; 447 | } 448 | 449 | public: 450 | void forwardToCore(CommandQEntry *ce, SessionContext &sc) 451 | { 452 | vector words= Cli::splitString(ce->command.c_str(), " \t\n:<>"); 453 | 454 | CoreInstance *ci= findInstance(sc.coreID); 455 | if(ci) 456 | { 457 | CoreCommandInfo *cci= findCoreCommand(words[0]); 458 | if(cci) 459 | { 460 | AccessLevel al= cci->accessLevel; 461 | if( ce->command.find(">")!=string::npos || ce->command.find("<")!=string::npos ) 462 | al= ACCESS_ADMIN; // i/o redirection requires admin level. 463 | if(sc.accessLevel>=al) 464 | { 465 | ci->queueCommand(ce); 466 | ci->flushCommandQ(*this); 467 | } 468 | else 469 | { 470 | sc.forwardStatusline(string(DENIED_STR) + format(_(" insufficient access level (command needs %s, you have %s)\n"), 471 | gAccessLevelNames[al], gAccessLevelNames[sc.accessLevel])); 472 | } 473 | } 474 | else 475 | { 476 | sc.commandNotFound(format(_("no such core command '%s'."), words[0].c_str())); 477 | } 478 | } 479 | else 480 | { 481 | sc.forwardStatusline(string(ERROR_STR) + format(_(" core process with ID %d has gone away\n"), sc.coreID)); 482 | flog(LOG_INFO, _("client %d has invalid coreID %d, zeroing.\n"), sc.clientID, sc.coreID); 483 | sc.coreID= 0; 484 | } 485 | 486 | delete ce; 487 | } 488 | 489 | // process a fully transferred command 490 | // deletes ce 491 | void processCommand(CommandQEntry *ce, SessionContext &sc) 492 | { 493 | vector words= Cli::splitString(ce->command.c_str(), " \t\n"); 494 | if(words.empty()) { delete(ce); return; } 495 | ServCmd *cmd= (ServCmd*)cli.findCommand(words[0]); 496 | if(cmd) 497 | { 498 | // execute server command 499 | sc.stats.servCommandsSent++; 500 | if(!ce->dataset.empty()) // currently, no server command takes a data set. 501 | sc.forwardStatusline(string(FAIL_STR) + " " + words[0] + _(" accepts no data set.\n")); 502 | else if( ce->command.find(">")!=string::npos || ce->command.find("<")!=string::npos ) 503 | sc.forwardStatusline(string(FAIL_STR) + _(" input/output of server commands can't be redirected.\n")); 504 | else cli.execute(cmd, words, sc); 505 | delete ce; 506 | } 507 | else if(sc.coreID) 508 | { 509 | forwardToCore(ce, sc); 510 | } 511 | else 512 | { 513 | // no server command and not connected to core 514 | sc.commandNotFound(format(_("no such server command '%s'."), words[0].c_str())); 515 | delete ce; 516 | } 517 | } 518 | private: 519 | 520 | // handle a line of text arriving from a client. 521 | void lineFromClient(string line, SessionContext &sc, double timestamp, bool fromServerQueue= false) 522 | { 523 | if(line.rfind('\n')!=line.size()-1) line.append("\n"); 524 | 525 | sc.stats.linesSent++; 526 | sc.stats.bytesSent+= line.length(); 527 | 528 | if(sc.curCommand) 529 | { 530 | if(sc.curCommand->acceptsData && (!sc.curCommand->dataFinished)) 531 | { 532 | sc.curCommand->appendToDataset(line); 533 | if(sc.curCommand->flushable()) 534 | { 535 | processCommand(sc.curCommand, sc); 536 | sc.curCommand= NULL; 537 | } 538 | } 539 | else 540 | { 541 | flog(LOG_INFO, "queuing: '%s", line.c_str()); 542 | sc.lineQueue.push(line); // must finish pending core commands first, queue this line for later processing 543 | } 544 | } 545 | else 546 | { 547 | //~ flog(LOG_INFO, "new command: %s", line.c_str()); 548 | // CoreInstance *ci= findInstance(sc.coreID); 549 | if(!fromServerQueue && (sc.lineQueue.size() || sc.isWaitingForCoreReply())) //(ci && ci->hasDataForClient(sc.clientID)))) 550 | { 551 | //flog(LOG_INFO, "queuing.\n"); 552 | sc.lineQueue.push(line); 553 | } 554 | else 555 | { 556 | CommandQEntry *ce= new CommandQEntry(sc.clientID, line); 557 | if(ce->flushable()) 558 | //flog(LOG_INFO, "flushable.\n"), 559 | processCommand(ce, sc); 560 | else 561 | //flog(LOG_INFO, "has data set.\n"), 562 | sc.curCommand= ce; 563 | } 564 | } 565 | } 566 | 567 | // handle a line of text arriving from a HTTP client 568 | void lineFromHTTPClient(string line, HTTPSessionContext &sc, double timestamp) 569 | { 570 | sc.http.request.push_back(line); 571 | if(line=="\n") // end of request. CR is removed by buffering code 572 | { 573 | sc.http.requestString= sc.http.request[0]; 574 | sc.http.request.clear(); // discard the rest of the header, as we don't currently use it. 575 | vector words= Cli::splitString(sc.http.requestString.c_str()); 576 | if(words.size()!=3) // this does not look like an HTTP request. disconnect the client. 577 | { 578 | flog(LOG_ERROR, _("bad HTTP request string, disconnecting.\n")); 579 | sc.forwardStatusline(string(FAIL_STR) + _(" bad HTTP request string.\n")); 580 | return; 581 | } 582 | transform(words[2].begin(), words[2].end(),words[2].begin(), ::toupper); 583 | if( (words[2]!="HTTP/1.0") && (words[2]!="HTTP/1.1") ) // accept HTTP/1.1 too, if only for debugging. 584 | { 585 | flog(LOG_ERROR, _("unknown HTTP version, disconnecting.\n")); 586 | sc.forwardStatusline(string(FAIL_STR) + _(" unknown HTTP version.\n")); 587 | return; 588 | } 589 | 590 | const char *uri= words[1].c_str(); 591 | int urilen= words[1].size(); 592 | string transformedURI; 593 | transformedURI.reserve(urilen); 594 | for(int i= 0; i % 603 | if(i corename, command 631 | vector uriwords= Cli::splitString(transformedURI.c_str(), "/"); 632 | 633 | if(uriwords.size()>=2) 634 | { 635 | string coreName= uriwords[0], 636 | command= transformedURI.substr(coreName.size()+1, transformedURI.size()-coreName.size()-1); 637 | 638 | // flog(LOG_INFO, "corename: '%s' command: '%s'\n", coreName.c_str(), command.c_str()); 639 | 640 | // immediately connect the client to the core named in the request string, 641 | // then execute the requested command. 642 | CoreInstance *ci= findNamedInstance(coreName); 643 | if(!ci) 644 | { 645 | sc.forwardStatusline(string(FAIL_STR) + " " + _("No such instance.\n")); 646 | return; 647 | } 648 | 649 | if(lineIndicatesDataset(command)) 650 | { 651 | sc.forwardStatusline(string(FAIL_STR) + _(" data sets not allowed in HTTP GET requests.\n")); 652 | return; 653 | } 654 | 655 | sc.coreID= ci->getID(); 656 | lineFromClient(command, sc, timestamp); 657 | } 658 | else 659 | { 660 | if(Cli::splitString(transformedURI.c_str()).size()) 661 | { 662 | if(lineIndicatesDataset(transformedURI)) 663 | { 664 | sc.forwardStatusline(string(FAIL_STR) + _(" data sets not allowed in HTTP GET requests.\n")); 665 | return; 666 | } 667 | 668 | // try to execute the request as one command. 669 | lineFromClient(transformedURI, sc, timestamp); 670 | } 671 | else 672 | { 673 | // empty request string received. return information and disconnect. 674 | flog(LOG_ERROR, _("empty HTTP request string, disconnecting.\n")); 675 | sc.forwardStatusline(format(_("%s this is the GraphServ HTTP module listening on port %d. " 676 | "protocol-version is %s. %d core instance(s) running, " 677 | "%d client connection(s) active including yours.\n"), 678 | SUCCESS_STR, httpPort, stringify(PROTOCOL_VERSION), coreInstances.size(), sessionContexts.size())); 679 | } 680 | } 681 | } 682 | } 683 | 684 | // called when a session socket is readable (level triggered) 685 | template 686 | void cb_sessionReadable(evutil_socket_t fd, short what) 687 | { 688 | const size_t BUFSIZE= 128; 689 | char buf[BUFSIZE]; 690 | SessionContext &sc= *libeventData.sessions[fd]; 691 | double time= getTime(); 692 | ssize_t sz= recv(fd, buf, sizeof(buf), 0); 693 | auto closeSession= [this] (SessionContext& sc) 694 | { 695 | removeSession(sc.clientID); 696 | }; 697 | if(sz==0) 698 | { 699 | flog(LOG_INFO, _("client %d: connection closed%s.\n"), sc.clientID, sc.shutdownTime? "": _(" by peer")); 700 | closeSession(sc); 701 | } 702 | else if(sz<0) 703 | { 704 | flog(LOG_ERROR, _("recv() error, client %d, %d bytes in write buffer, %s\n"), sc.clientID, sc.getWritebufferSize(), strerror(errno)); 705 | closeSession(sc); 706 | } 707 | else 708 | { 709 | for(ssize_t i= 0; i 732 | void cb_sessionWritable(evutil_socket_t fd, short what) 733 | { 734 | flog(LOG_INFO, "session context writable event\n"); 735 | libeventData.sessions[fd]->flush(); 736 | } 737 | 738 | // called when a core pipe is readable (level triggered) 739 | 740 | // XXXXXXXXXX todo: handle different CB types (all callbacks) 741 | void cb_coreReadable(evutil_socket_t fd, short what) 742 | { 743 | CoreInstance *ci= libeventData.cores[fd]; 744 | if(fd==ci->getReadFd()) 745 | { 746 | const size_t BUFSIZE= 128; 747 | char buf[BUFSIZE]; 748 | ssize_t sz= read(ci->getReadFd(), buf, sizeof(buf)); 749 | double time= getTime(); 750 | if(sz==0) 751 | { 752 | int status; 753 | waitpid(ci->getPid(), &status, 0); 754 | if(WIFEXITED(status)) 755 | { 756 | flog(LOG_INFO, "core %s (ID %u, pid %d) exited with status %d\n", ci->getName().c_str(), ci->getID(), (int)ci->getPid(), WEXITSTATUS(status)); 757 | } 758 | else if(WIFSIGNALED(status)) 759 | { 760 | flog(LOG_INFO, "core %s (ID %u, pid %d) exited due to signal %d (%s)%s\n", ci->getName().c_str(), ci->getID(), (int)ci->getPid(), 761 | WTERMSIG(status), strsignal(WTERMSIG(status)), 762 | #ifdef WCOREDUMP 763 | WCOREDUMP(status)? ", core dumped": ", core not dumped" 764 | #else 765 | "" 766 | #endif 767 | ); 768 | 769 | } 770 | 771 | removeCoreInstance(ci); 772 | } 773 | else if(sz<0) 774 | { 775 | flog(LOG_ERROR, "i/o error, core %s: %s\n", ci->getName().c_str(), strerror(errno)); 776 | removeCoreInstance(ci); 777 | } 778 | else 779 | { 780 | for(ssize_t i= 0; ilinebuf+= c; 785 | if(c=='\n') 786 | { 787 | SessionContext *sc= findClient(ci->getLastClientID()); 788 | bool clientWasWaiting= (sc && sc->isWaitingForCoreReply()); 789 | ci->lineFromCore(ci->linebuf, *this); 790 | ci->linebuf.clear(); 791 | // if this was the last line the client was waiting for, 792 | // execute its queued commands now. 793 | if( clientWasWaiting ) 794 | while(!sc->lineQueue.empty() && (!sc->isWaitingForCoreReply())) 795 | { 796 | string& line= sc->lineQueue.front(); 797 | flog(LOG_INFO, "execing queued line from client: '%s", line.c_str()); 798 | lineFromClient(line, *sc, time, true); 799 | sc->lineQueue.pop(); 800 | } 801 | } 802 | } 803 | } 804 | } 805 | else if(fd==ci->getStderrReadFd()) 806 | { 807 | deque lines= ci->stderrQ.nextLines(ci->getStderrReadFd()); 808 | for(deque::const_iterator it= lines.begin(); it!=lines.end(); ++it) 809 | flog(LOG_INFO, "[%s] %s", ci->getName().c_str(), it->c_str()); 810 | } 811 | } 812 | 813 | // called when a core pipe is writable (edge triggered) 814 | void cb_coreWritable(evutil_socket_t fd, short what) 815 | { 816 | //~ flog(LOG_INFO, "core writable event, ID %d, name %s. commandQ size: %d, flushable: %s, expectingReply: %s, expectingDataset: %s\n", 817 | //~ libeventData.cores[fd]->getID(), libeventData.cores[fd]->getName().c_str(), 818 | //~ libeventData.cores[fd]->commandQ.size(), libeventData.cores[fd]->commandQ.front().flushable()? "true": "false", 819 | //~ libeventData.cores[fd]->expectingReply? "true": "false", libeventData.cores[fd]->expectingDataset? "true": "false"); 820 | libeventData.cores[fd]->flushCommandQ(*this); 821 | libeventData.cores[fd]->flush(); 822 | //~ flog(LOG_INFO, "after flushCommandQ: commandQ size: %d, flushable: %s, expectingReply: %s, expectingDataset: %s\n", 823 | //~ libeventData.cores[fd]->commandQ.size(), libeventData.cores[fd]->commandQ.front().flushable()? "true": "false", 824 | //~ libeventData.cores[fd]->expectingReply? "true": "false", libeventData.cores[fd]->expectingDataset? "true": "false" ); 825 | } 826 | 827 | // called when something connects to either of the listen sockets 828 | template 829 | void cb_connect(evutil_socket_t fd, short what) 830 | { 831 | flog(LOG_INFO, "cb_connect(): fd=%d, what=%d\n", fd, what); 832 | SessionContext *sc= acceptConnection(fd, CONNTYPE); 833 | if(sc) 834 | { 835 | sc->sockfdRead= dup(sc->sockfd); 836 | libeventData.sessions[sc->sockfd]= sc; 837 | libeventData.sessions[sc->sockfdRead]= sc; 838 | sc->readEvent= event_new(libeventData.base, sc->sockfdRead, EV_READ|EV_PERSIST, [](evutil_socket_t fd, short what, void *arg) 839 | { 840 | ((Graphserv*)arg)->cb_sessionReadable(fd, what); 841 | }, this); 842 | sc->writeEvent= event_new(libeventData.base, sc->sockfd, EV_WRITE|EV_PERSIST|EV_ET, [](evutil_socket_t fd, short what, void *arg) 843 | { 844 | ((Graphserv*)arg)->cb_sessionWritable(fd, what); 845 | }, this); 846 | event_add(sc->readEvent, nullptr); 847 | event_add(sc->writeEvent, nullptr); 848 | } 849 | else 850 | { 851 | flog(LOG_ERROR, _("couldn't create connection.\n")); 852 | //~ if(errno==EMFILE) 853 | //~ { 854 | //~ double defer= 3.0; 855 | //~ flog(LOG_ERROR, _("too many open files. deferring new connections for %.0f seconds.\n"), defer); 856 | //~ deferNewConnectionsUntil= time + defer; 857 | //~ } 858 | } 859 | } 860 | 861 | bool mainloop_libevent() 862 | { 863 | #ifdef DEBUG_EVENTS 864 | event_enable_debug_mode(); 865 | #endif 866 | 867 | flog(LOG_INFO, "compiled libevent version: %s\n", LIBEVENT_VERSION); 868 | flog(LOG_INFO, "runtime libevent version: %s\n", event_get_version()); 869 | 870 | event_config *cfg= event_config_new(); 871 | if(!cfg) 872 | throw std::runtime_error("event_config_new() failed"); 873 | event_config_require_features(cfg, EV_FEATURE_ET); 874 | if(!(libeventData.base= event_base_new_with_config(cfg))) 875 | throw std::runtime_error("event_base_new_with_config() failed"); 876 | event_config_free(cfg); 877 | 878 | int i; 879 | const char **methods = event_get_supported_methods(); 880 | flog(LOG_INFO, "Starting Libevent %s. Available methods are:\n", event_get_version()); 881 | for (i=0; methods[i] != NULL; ++i) 882 | flog(LOG_INFO, " %s\n", methods[i]); 883 | flog(LOG_INFO, "Using Libevent with backend method %s.\n", event_base_get_method(libeventData.base)); 884 | int f = event_base_get_features(libeventData.base); 885 | if ((f & EV_FEATURE_ET)) 886 | flog(LOG_INFO, " Edge-triggered events are supported.\n"); 887 | if ((f & EV_FEATURE_O1)) 888 | flog(LOG_INFO, " O(1) event notification is supported.\n"); 889 | if ((f & EV_FEATURE_FDS)) 890 | flog(LOG_INFO, " All FD types are supported.\n"); 891 | 892 | event_callback_fn listen_cb= [] (evutil_socket_t fd, short what, void *arg) 893 | { 894 | Graphserv *self= (Graphserv*)arg; 895 | self->cb_connect(fd, what); 896 | }; 897 | event_callback_fn http_cb= [] (evutil_socket_t fd, short what, void *arg) 898 | { 899 | Graphserv *self= (Graphserv*)arg; 900 | self->cb_connect(fd, what); 901 | }; 902 | event *ev= event_new(libeventData.base, listenSocket, EV_READ|EV_PERSIST, listen_cb, this); 903 | event_add(ev, nullptr); 904 | ev= event_new(libeventData.base, httpSocket, EV_READ|EV_PERSIST, http_cb, this); 905 | event_add(ev, nullptr); 906 | 907 | while(!quit) 908 | { 909 | event_base_loop(libeventData.base, EVLOOP_ONCE); 910 | // go through any HTTP session contexts immediately after i/o. 911 | // XXX todo: doing this after write CB / in HTTPSessionContext::forwardDataset() etc. could be slightly more efficient 912 | for( map::iterator i= sessionContexts.begin(); i!=sessionContexts.end(); ++i ) 913 | { 914 | SessionContext *sc= i->second; 915 | CoreInstance *ci; 916 | // HTTP clients are disconnected once we don't have any more output for them. 917 | if( sc->connectionType==CONN_HTTP && 918 | ((HTTPSessionContext*)sc)->conversationFinished && 919 | sc->writeBufferEmpty() && 920 | ((ci= findInstance(sc->coreID))==NULL || ci->hasDataForClient(sc->clientID)==false) ) 921 | { 922 | if(!sc->shutdownTime) 923 | shutdownClient(sc); 924 | } 925 | } 926 | } 927 | 928 | return true; 929 | } 930 | 931 | bool mainloop_select() 932 | { 933 | fd_set readfds, writefds; 934 | int maxfd; 935 | double deferNewConnectionsUntil= 0; // defer accept() calls. set if open files limit is hit. 936 | 937 | flog(LOG_INFO, "entering main loop. TCP port: %d, HTTP port: %d\n", tcpPort, httpPort); 938 | while(!quit) 939 | { 940 | double time= getTime(); 941 | 942 | FD_ZERO(&readfds); 943 | FD_ZERO(&writefds); 944 | 945 | maxfd= 0; 946 | 947 | // when open files limit is hit, new connections will be deferred for a few seconds 948 | if(deferNewConnectionsUntil < time) 949 | { 950 | if(listenSocket) fd_add(readfds, listenSocket, maxfd); 951 | if(httpSocket) fd_add(readfds, httpSocket, maxfd); 952 | } 953 | 954 | // deferred removal of clients 955 | for(set::iterator i= clientsToRemove.begin(); i!=clientsToRemove.end(); ++i) 956 | removeSession(*i); 957 | clientsToRemove.clear(); 958 | 959 | // init fd set for select: add client fds 960 | for( map::iterator i= sessionContexts.begin(); i!=sessionContexts.end(); ++i ) 961 | { 962 | SessionContext *sc= i->second; 963 | double d= time-sc->stats.lastTime; 964 | if(d>10.0) 965 | { 966 | sc->stats.normalize(time); 967 | // flog(LOG_INFO, "client %u: bytesSent %.2f, linesQueued %.2f, coreCommandsSent %.2f, servCommandsSent %.2f\n", 968 | // sc->clientID, sc->stats.bytesSent, sc->stats.linesQueued, sc->stats.coreCommandsSent, sc->stats.servCommandsSent); 969 | // testing this to prevent flooding. 970 | //~ if(sc->stats.linesQueued>5000) { flog(LOG_INFO, "choke\n"); sc->chokeTime= time+10.0; } 971 | sc->stats.reset(); 972 | sc->stats.lastTime= time; 973 | } 974 | if(sc->chokeTimesockfd, maxfd); 976 | else 977 | flog(LOG_INFO, "not reading from client %u (flood).\n", sc->clientID); 978 | // only add write fd if there is something to write 979 | if(!sc->writeBufferEmpty()) 980 | fd_add(writefds, sc->sockfd, maxfd); 981 | } 982 | 983 | // init fd set for select: add core fds 984 | for( map::iterator i= coreInstances.begin(); i!=coreInstances.end(); ++i ) 985 | { 986 | CoreInstance *ci= i->second; 987 | fd_add(readfds, ci->getReadFd(), maxfd); 988 | fd_add(readfds, ci->getStderrReadFd(), maxfd); 989 | ci->flushCommandQ(*this); 990 | // only add write fd if there is something to write 991 | if(!ci->writeBufferEmpty()) 992 | fd_add(writefds, ci->getWriteFd(), maxfd); 993 | } 994 | 995 | struct timeval timeout; 996 | timeout.tv_sec= 2; 997 | timeout.tv_usec= 0; 998 | int r= select(maxfd+1, &readfds, &writefds, 0, &timeout); 999 | if(r<0) 1000 | { 1001 | switch(errno) 1002 | { 1003 | case EBADF: 1004 | logerror("select()"); 1005 | // a file descriptor is bad, find out which and remove the client or core. 1006 | for( map::iterator i= sessionContexts.begin(); i!=sessionContexts.end(); ++i ) 1007 | if( !i->second->writeBufferEmpty() && fcntl(i->second->sockfd, F_GETFL)==-1 ) 1008 | flog(LOG_ERROR, _("bad fd, removing client %d.\n"), i->second->clientID), 1009 | forceClientDisconnect(i->second); 1010 | for( map::iterator i= coreInstances.begin(); i!=coreInstances.end(); ++i ) 1011 | if( fcntl(i->second->getReadFd(), F_GETFL)==-1 || 1012 | (!i->second->writeBufferEmpty() && fcntl(i->second->getWriteFd(), F_GETFL)==-1) ) 1013 | flog(LOG_ERROR, _("bad fd, removing core %d.\n"), i->second->getID()), 1014 | removeCoreInstance(i->second); 1015 | continue; 1016 | 1017 | case EINTR: 1018 | continue; 1019 | 1020 | default: 1021 | logerror("select()"); 1022 | return false; 1023 | } 1024 | } 1025 | 1026 | time= getTime(); 1027 | 1028 | // check for incoming line-based or http connections. 1029 | struct { int socket; ConnectionType conntype; } socks[]= { { listenSocket, CONN_TCP }, { httpSocket, CONN_HTTP } }; 1030 | for(auto& i: socks) 1031 | { 1032 | if(i.socket && FD_ISSET(i.socket, &readfds)) 1033 | if(!acceptConnection(i.socket, i.conntype)) 1034 | { 1035 | flog(LOG_ERROR, _("couldn't create connection.\n")); 1036 | if(errno==EMFILE) 1037 | { 1038 | double defer= 3.0; 1039 | flog(LOG_ERROR, _("too many open files. deferring new connections for %.0f seconds.\n"), defer); 1040 | deferNewConnectionsUntil= time + defer; 1041 | } 1042 | } 1043 | } 1044 | 1045 | // loop through all the session contexts, handle incoming data, flush outgoing data if possible. 1046 | for( map::iterator it= sessionContexts.begin(); it!=sessionContexts.end(); ++it ) 1047 | { 1048 | SessionContext &sc= *it->second; 1049 | int sockfd= sc.sockfd; 1050 | if(FD_ISSET(sockfd, &readfds)) 1051 | { 1052 | const size_t BUFSIZE= 128; 1053 | char buf[BUFSIZE]; 1054 | ssize_t sz= recv(sockfd, buf, sizeof(buf), 0); 1055 | if(sz==0) 1056 | { 1057 | flog(LOG_INFO, _("client %d: connection closed%s.\n"), sc.clientID, sc.shutdownTime? "": _(" by peer")); 1058 | clientsToRemove.insert(sc.clientID); 1059 | } 1060 | else if(sz<0) 1061 | { 1062 | flog(LOG_ERROR, _("recv() error, client %d, %d bytes in write buffer, %s\n"), sc.clientID, sc.getWritebufferSize(), strerror(errno)); 1063 | clientsToRemove.insert(sc.clientID); 1064 | } 1065 | else 1066 | { 1067 | for(ssize_t i= 0; i coresToRemove; 1093 | 1094 | // loop through all the core instances, handle incoming data, flush outgoing data if possible. 1095 | for( map::iterator i= coreInstances.begin(); i!=coreInstances.end(); ++i ) 1096 | { 1097 | CoreInstance *ci= i->second; 1098 | if(FD_ISSET(ci->getReadFd(), &readfds)) 1099 | { 1100 | const size_t BUFSIZE= 1024; 1101 | char buf[BUFSIZE]; 1102 | ssize_t sz= read(ci->getReadFd(), buf, sizeof(buf)); 1103 | if(sz==0) 1104 | { 1105 | flog(LOG_INFO, "core %s (ID %u, pid %d) has exited\n", ci->getName().c_str(), ci->getID(), (int)ci->getPid()); 1106 | int status; 1107 | waitpid(ci->getPid(), &status, 0); // un-zombify 1108 | coresToRemove.push_back(ci); 1109 | } 1110 | else if(sz<0) 1111 | { 1112 | flog(LOG_ERROR, "i/o error, core %s: %s\n", ci->getName().c_str(), strerror(errno)); 1113 | coresToRemove.push_back(ci); 1114 | } 1115 | else 1116 | { 1117 | for(ssize_t i= 0; ilinebuf+= c; 1122 | if(c=='\n') 1123 | { 1124 | SessionContext *sc= findClient(ci->getLastClientID()); 1125 | bool clientWasWaiting= (sc && sc->isWaitingForCoreReply()); 1126 | ci->lineFromCore(ci->linebuf, *this); 1127 | ci->linebuf.clear(); 1128 | // if this was the last line the client was waiting for, 1129 | // execute its queued commands now. 1130 | if( clientWasWaiting ) 1131 | while(!sc->lineQueue.empty() && (!sc->isWaitingForCoreReply())) 1132 | { 1133 | string& line= sc->lineQueue.front(); 1134 | flog(LOG_INFO, "execing queued line from client: '%s", line.c_str()); 1135 | lineFromClient(line, *sc, time, true); 1136 | sc->lineQueue.pop(); 1137 | } 1138 | } 1139 | } 1140 | } 1141 | } 1142 | else if(FD_ISSET(ci->getStderrReadFd(), &readfds)) 1143 | { 1144 | deque lines= ci->stderrQ.nextLines(ci->getStderrReadFd()); 1145 | for(deque::const_iterator it= lines.begin(); it!=lines.end(); ++it) 1146 | flog(LOG_INFO, "[%s] %s", ci->getName().c_str(), it->c_str()); 1147 | } 1148 | 1149 | if(FD_ISSET(ci->getWriteFd(), &writefds)) 1150 | ci->flush(); 1151 | } 1152 | // remove outside of loop to avoid invalidating iterators 1153 | for(size_t i= 0; i::iterator i= sessionContexts.begin(); i!=sessionContexts.end(); ++i ) 1158 | { 1159 | SessionContext *sc= i->second; 1160 | CoreInstance *ci; 1161 | // HTTP clients are disconnected once we don't have any more output for them. 1162 | if( sc->connectionType==CONN_HTTP && 1163 | ((HTTPSessionContext*)sc)->conversationFinished && 1164 | sc->writeBufferEmpty() && 1165 | ((ci= findInstance(sc->coreID))==NULL || ci->hasDataForClient(sc->clientID)==false) ) 1166 | { 1167 | if(!sc->shutdownTime) 1168 | shutdownClient(sc); 1169 | } 1170 | } 1171 | } 1172 | 1173 | return true; 1174 | } 1175 | 1176 | friend class ccInfo; 1177 | friend class ccServerStats; 1178 | }; 1179 | 1180 | #endif // SERVAPP_H 1181 | --------------------------------------------------------------------------------