source: trunk/packages/vizservers/nanovis/nanovisServer.cpp @ 4107

Last change on this file since 4107 was 4107, checked in by ldelgass, 11 years ago

Add command-line options to nanovis/geovis/vtkvis servers to allow setting
file descriptors to use for client IO (i.e. which fds are used by nanoscale
to dup the socket). Must be 0-4 and check that trace log fd isn't used for
client IO.

  • Property svn:eol-style set to native
File size: 15.8 KB
Line 
1/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2/*
3 * Copyright (C) 2004-2013  HUBzero Foundation, LLC
4 *
5 */
6
7#include <cassert>
8#include <cstdio>
9#include <cerrno>
10#include <cstring>
11#include <csignal>
12
13#include <fcntl.h>
14#include <getopt.h>
15#include <sys/time.h>
16#include <sys/times.h>
17#include <sys/uio.h> // for readv/writev
18#include <unistd.h>
19
20#include <sstream>
21
22#include <tcl.h>
23
24#include <GL/glew.h>
25#include <GL/glut.h>
26
27#include <util/FilePath.h>
28
29#include "nanovis.h"
30#include "nanovisServer.h"
31#include "define.h"
32#include "Command.h"
33#include "PPMWriter.h"
34#include "ReadBuffer.h"
35#include "Shader.h"
36#ifdef USE_THREADS
37#include <pthread.h>
38#include "ResponseQueue.h"
39#endif
40#include "Trace.h"
41
42using namespace nv;
43using namespace nv::util;
44
45Stats nv::g_stats;
46int nv::g_statsFile = -1; ///< Stats output file descriptor.
47
48int nv::g_fdIn = STDIN_FILENO;     ///< Input file descriptor
49int nv::g_fdOut = STDOUT_FILENO;   ///< Output file descriptor
50FILE *nv::g_fOut = NULL;           ///< Output file handle
51FILE *nv::g_fLog = NULL;           ///< Trace logging file handle
52ReadBuffer *nv::g_inBufPtr = NULL; ///< Socket read buffer
53#ifdef USE_THREADS
54ResponseQueue *nv::g_queue = NULL;
55#endif
56
57#ifdef USE_THREADS
58
59static void
60queueFrame(ResponseQueue *queue, unsigned char *imgData)
61{
62    queuePPM(queue, "nv>image -type image -bytes",
63             imgData,
64             NanoVis::winWidth,
65             NanoVis::winHeight);
66}
67
68#else
69
70static void
71writeFrame(int fd, unsigned char *imgData)
72{
73    writePPM(fd, "nv>image -type image -bytes",
74             imgData,
75             NanoVis::winWidth,
76             NanoVis::winHeight);
77}
78
79#endif /*USE_THREADS*/
80
81static int
82sendAck()
83{
84    std::ostringstream oss;
85    oss << "nv>ok -token " << g_stats.nCommands <<  "\n";
86    int nBytes = oss.str().length();
87
88    TRACE("Sending OK for commands through %lu", g_stats.nCommands);
89#ifdef USE_THREADS
90    queueResponse(oss.str().c_str(), nBytes, Response::VOLATILE, Response::OK);
91#else
92    if (write(g_fdOut, oss.str().c_str(), nBytes) < 0) {
93        ERROR("write failed: %s", strerror(errno));
94        return -1;
95    }
96#endif
97    return 0;
98}
99
100#ifdef KEEPSTATS
101
102#ifndef STATSDIR
103#define STATSDIR        "/var/tmp/visservers"
104#endif  /*STATSDIR*/
105
106int
107nv::getStatsFile(Tcl_Interp *interp, Tcl_Obj *objPtr)
108{
109    Tcl_DString ds;
110    Tcl_Obj **objv;
111    int objc;
112    int i;
113    char fileName[33];
114    const char *path;
115    md5_state_t state;
116    md5_byte_t digest[16];
117    char *string;
118    int length;
119
120    if ((objPtr == NULL) || (g_statsFile >= 0)) {
121        return g_statsFile;
122    }
123    if (Tcl_ListObjGetElements(interp, objPtr, &objc, &objv) != TCL_OK) {
124        return -1;
125    }
126    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("pid", 3));
127    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewIntObj(getpid()));
128    string = Tcl_GetStringFromObj(objPtr, &length);
129
130    md5_init(&state);
131    md5_append(&state, (const md5_byte_t *)string, length);
132    md5_finish(&state, digest);
133    for (i = 0; i < 16; i++) {
134        sprintf(fileName + i * 2, "%02x", digest[i]);
135    }
136    Tcl_DStringInit(&ds);
137    Tcl_DStringAppend(&ds, STATSDIR, -1);
138    Tcl_DStringAppend(&ds, "/", 1);
139    Tcl_DStringAppend(&ds, fileName, 32);
140    path = Tcl_DStringValue(&ds);
141
142    g_statsFile = open(path, O_EXCL | O_CREAT | O_WRONLY, 0600);
143    Tcl_DStringFree(&ds);
144    if (g_statsFile < 0) {
145        ERROR("can't open \"%s\": %s", fileName, strerror(errno));
146        return -1;
147    }
148    return g_statsFile;
149}
150
151int
152nv::writeToStatsFile(int f, const char *s, size_t length)
153{
154    if (f >= 0) {
155        ssize_t numWritten;
156
157        numWritten = write(f, s, length);
158        if (numWritten == (ssize_t)length) {
159            close(dup(f));
160        }
161    }
162    return 0;
163}
164
165static int
166serverStats(int code)
167{
168    double start, finish;
169    char buf[BUFSIZ];
170    Tcl_DString ds;
171    int result;
172    int f;
173
174    {
175        struct timeval tv;
176
177        /* Get ending time.  */
178        gettimeofday(&tv, NULL);
179        finish = CVT2SECS(tv);
180        tv = g_stats.start;
181        start = CVT2SECS(tv);
182    }
183    /*
184     * Session information:
185     *   - Name of render server
186     *   - Process ID
187     *   - Hostname where server is running
188     *   - Start date of session
189     *   - Start date of session in seconds
190     *   - Number of frames returned
191     *   - Number of bytes total returned (in frames)
192     *   - Number of commands received
193     *   - Total elapsed time of all commands
194     *   - Total elapsed time of session
195     *   - Exit code of vizserver
196     *   - User time
197     *   - System time
198     *   - User time of children
199     *   - System time of children
200     */
201
202    Tcl_DStringInit(&ds);
203   
204    Tcl_DStringAppendElement(&ds, "render_stop");
205    /* renderer */
206    Tcl_DStringAppendElement(&ds, "renderer");
207    Tcl_DStringAppendElement(&ds, "nanovis");
208    /* pid */
209    Tcl_DStringAppendElement(&ds, "pid");
210    sprintf(buf, "%d", getpid());
211    Tcl_DStringAppendElement(&ds, buf);
212    /* host */
213    Tcl_DStringAppendElement(&ds, "host");
214    gethostname(buf, BUFSIZ-1);
215    buf[BUFSIZ-1] = '\0';
216    Tcl_DStringAppendElement(&ds, buf);
217    /* date */
218    Tcl_DStringAppendElement(&ds, "date");
219    strcpy(buf, ctime(&g_stats.start.tv_sec));
220    buf[strlen(buf) - 1] = '\0';
221    Tcl_DStringAppendElement(&ds, buf);
222    /* date_secs */
223    Tcl_DStringAppendElement(&ds, "date_secs");
224    sprintf(buf, "%ld", g_stats.start.tv_sec);
225    Tcl_DStringAppendElement(&ds, buf);
226    /* num_frames */
227    Tcl_DStringAppendElement(&ds, "num_frames");
228    sprintf(buf, "%lu", (unsigned long int)g_stats.nFrames);
229    Tcl_DStringAppendElement(&ds, buf);
230    /* frame_bytes */
231    Tcl_DStringAppendElement(&ds, "frame_bytes");
232    sprintf(buf, "%lu", (unsigned long int)g_stats.nFrameBytes);
233    Tcl_DStringAppendElement(&ds, buf);
234    /* num_commands */
235    Tcl_DStringAppendElement(&ds, "num_commands");
236    sprintf(buf, "%lu", (unsigned long int)g_stats.nCommands);
237    Tcl_DStringAppendElement(&ds, buf);
238    /* cmd_time */
239    Tcl_DStringAppendElement(&ds, "cmd_time");
240    sprintf(buf, "%g", g_stats.cmdTime);
241    Tcl_DStringAppendElement(&ds, buf);
242    /* session_time */
243    Tcl_DStringAppendElement(&ds, "session_time");
244    sprintf(buf, "%g", finish - start);
245    Tcl_DStringAppendElement(&ds, buf);
246    /* status */
247    Tcl_DStringAppendElement(&ds, "status");
248    sprintf(buf, "%d", code);
249    Tcl_DStringAppendElement(&ds, buf);
250    {
251        long clocksPerSec = sysconf(_SC_CLK_TCK);
252        double clockRes = 1.0 / clocksPerSec;
253        struct tms tms;
254
255        memset(&tms, 0, sizeof(tms));
256        times(&tms);
257        /* utime */
258        Tcl_DStringAppendElement(&ds, "utime");
259        sprintf(buf, "%g", tms.tms_utime * clockRes);
260        Tcl_DStringAppendElement(&ds, buf);
261        /* stime */
262        Tcl_DStringAppendElement(&ds, "stime");
263        sprintf(buf, "%g", tms.tms_stime * clockRes);
264        Tcl_DStringAppendElement(&ds, buf);
265        /* cutime */
266        Tcl_DStringAppendElement(&ds, "cutime");
267        sprintf(buf, "%g", tms.tms_cutime * clockRes);
268        Tcl_DStringAppendElement(&ds, buf);
269        /* cstime */
270        Tcl_DStringAppendElement(&ds, "cstime");
271        sprintf(buf, "%g", tms.tms_cstime * clockRes);
272        Tcl_DStringAppendElement(&ds, buf);
273    }
274    Tcl_DStringAppend(&ds, "\n", -1);
275    f = getStatsFile(NULL, NULL);
276    result = writeToStatsFile(f, Tcl_DStringValue(&ds),
277                              Tcl_DStringLength(&ds));
278    close(f);
279    Tcl_DStringFree(&ds);
280    return result;
281}
282
283#endif
284
285/**
286 * \brief Send a command with data payload
287 *
288 * data pointer is freed on completion of the response
289 */
290void
291nv::sendDataToClient(const char *command, char *data, size_t dlen)
292{
293#ifdef USE_THREADS
294    char *buf = (char *)malloc(strlen(command) + dlen);
295    memcpy(buf, command, strlen(command));
296    memcpy(buf + strlen(command), data, dlen);
297    queueResponse(buf, strlen(command) + dlen, Response::DYNAMIC);
298#else
299    size_t numRecords = 2;
300    struct iovec *iov = new iovec[numRecords];
301
302    // Write the nanovisviewer command, then the image header and data.
303    // Command
304    iov[0].iov_base = const_cast<char *>(command);
305    iov[0].iov_len = strlen(command);
306    // Data
307    iov[1].iov_base = data;
308    iov[1].iov_len = dlen;
309    if (writev(nv::g_fdOut, iov, numRecords) < 0) {
310        ERROR("write failed: %s", strerror(errno));
311    }
312    delete [] iov;
313    free(data);
314#endif
315}
316
317static void
318initService()
319{
320    g_fOut = fdopen(g_fdOut, "w");
321    // If running without socket, use stdout for debugging
322    if (g_fOut == NULL && g_fdOut != STDOUT_FILENO) {
323        g_fdOut = STDOUT_FILENO;
324        g_fOut = fdopen(g_fdOut, "w");
325    }
326
327    const char* user = getenv("USER");
328    char* logName = NULL;
329    int logNameLen = 0;
330
331    if (user == NULL) {
332        logNameLen = 20+1;
333        logName = (char *)calloc(logNameLen, sizeof(char));
334        strncpy(logName, "/tmp/nanovis_log.txt", logNameLen);
335    } else {
336        logNameLen = 17+1+strlen(user);
337        logName = (char *)calloc(logNameLen, sizeof(char));
338        strncpy(logName, "/tmp/nanovis_log_", logNameLen);
339        strncat(logName, user, strlen(user));
340    }
341
342    // open log and map stderr to log file
343    g_fLog = fopen(logName, "w");
344    dup2(fileno(g_fLog), STDERR_FILENO);
345    // If we are writing to socket, map stdout to log
346    if (g_fdOut != STDOUT_FILENO) {
347        dup2(fileno(g_fLog), STDOUT_FILENO);
348    }
349
350    fflush(stdout);
351
352    // clean up malloc'd memory
353    if (logName != NULL) {
354        free(logName);
355    }
356}
357
358static void
359exitService(int code)
360{
361    TRACE("Enter: %d", code);
362
363    NanoVis::removeAllData();
364
365    Shader::exit();
366
367    //close log file
368    if (g_fLog != NULL) {
369        fclose(g_fLog);
370        g_fLog = NULL;
371    }
372
373#ifdef KEEPSTATS
374    serverStats(code);
375#endif
376    closelog();
377
378    exit(code);
379}
380
381static void
382idle()
383{
384    TRACE("Enter");
385
386    glutSetWindow(NanoVis::renderWindow);
387
388    if (processCommands(NanoVis::interp, g_inBufPtr, g_fdOut) < 0) {
389        exitService(1);
390    }
391
392    NanoVis::update();
393    NanoVis::bindOffscreenBuffer();
394    NanoVis::render();
395    bool renderedSomething = true;
396    if (renderedSomething) {
397        TRACE("Rendering new frame");
398        NanoVis::readScreen();
399#ifdef USE_THREADS
400        queueFrame(g_queue, NanoVis::screenBuffer);
401#else
402        writeFrame(g_fdOut, NanoVis::screenBuffer);
403#endif
404        g_stats.nFrames++;
405        g_stats.nFrameBytes += NanoVis::winWidth * NanoVis::winHeight * 3;
406    } else {
407        TRACE("No render required");
408        sendAck();
409    }
410
411    if (g_inBufPtr->status() == ReadBuffer::ENDFILE) {
412        exitService(0);
413    }
414
415    TRACE("Leave");
416}
417
418#ifdef USE_THREADS
419
420static void *
421writerThread(void *clientData)
422{
423    ResponseQueue *queue = (ResponseQueue *)clientData;
424
425    TRACE("Starting writer thread");
426    for (;;) {
427        Response *response = queue->dequeue();
428        if (response == NULL)
429            continue;
430        if (fwrite(response->message(), sizeof(char), response->length(),
431                   g_fOut) != response->length()) {
432            ERROR("short write while trying to write %ld bytes",
433                  response->length());
434        }
435        fflush(g_fOut);
436        TRACE("Wrote response of type %d", response->type());
437        delete response;
438        if (feof(g_fOut))
439            break;
440    }   
441    return NULL;
442}
443
444#endif  /*USE_THREADS*/
445
446static
447void shaderErrorCallback(void)
448{
449    if (!Shader::printErrorInfo()) {
450        TRACE("Shader error, exiting...");
451        exitService(1);
452    }
453}
454
455static
456void reshape(int width, int height)
457{
458    NanoVis::resizeOffscreenBuffer(width, height);
459}
460
461int
462main(int argc, char **argv)
463{
464    // Ignore SIGPIPE.  **Is this needed? **
465    signal(SIGPIPE, SIG_IGN);
466
467    const char *resourcePath = NULL;
468    while (1) {
469        static struct option long_options[] = {
470            {"debug",   no_argument,       NULL, 'd'},
471            {"path",    required_argument, NULL, 'p'},
472            {0, 0, 0, 0}
473        };
474        int option_index = 0;
475        int c = getopt_long(argc, argv, "dp:i:o:", long_options, &option_index);
476        if (c == -1) {
477            break;
478        }
479        switch (c) {
480        case 'd':
481            NanoVis::debugFlag = true;
482            break;
483        case 'p':
484            resourcePath = optarg;
485            break;
486        case 'i': {
487            int fd = atoi(optarg);
488            if (fd >=0 && fd < 5) {
489                g_fdIn = fd;
490            }
491        }
492            break;
493        case 'o': {
494            int fd = atoi(optarg);
495            if (fd >=0 && fd < 5) {
496                g_fdOut = fd;
497            }
498        }
499            break;
500        case '?':
501            break;
502        default:
503            return 1;
504        }
505    }
506
507    initService();
508    initLog();
509
510    memset(&g_stats, 0, sizeof(g_stats));
511    gettimeofday(&g_stats.start, NULL);
512
513    TRACE("Starting NanoVis Server");
514    if (NanoVis::debugFlag) {
515        TRACE("Debugging on");
516    }
517
518    // Sanity check: log descriptor can't be used for client IO
519    if (fileno(g_fLog) == g_fdIn) {
520        ERROR("Invalid input file descriptor");
521        return 1;
522    }
523    if (fileno(g_fLog) == g_fdOut) {
524        ERROR("Invalid output file descriptor");
525        return 1;
526    }
527    TRACE("File descriptors: in %d out %d log %d", g_fdIn, g_fdOut, fileno(g_fLog));
528
529    /* This synchronizes the client with the server, so that the client
530     * doesn't start writing commands before the server is ready. It could
531     * also be used to supply information about the server (version, memory
532     * size, etc). */
533    fprintf(g_fOut, "NanoVis %s (build %s)\n", NANOVIS_VERSION_STRING, SVN_VERSION);
534    fflush(g_fOut);
535
536    g_inBufPtr = new ReadBuffer(g_fdIn, 1<<12);
537
538    Tcl_Interp *interp = Tcl_CreateInterp();
539    ClientData clientData = NULL;
540#ifdef USE_THREADS
541    g_queue = new ResponseQueue();
542    clientData = (ClientData)g_queue;
543    initTcl(interp, clientData);
544
545    pthread_t writerThreadId;
546    if (pthread_create(&writerThreadId, NULL, &writerThread, g_queue) < 0) {
547        ERROR("Can't create writer thread: %s", strerror(errno));
548    }
549#else
550    initTcl(interp, clientData);
551#endif
552    NanoVis::interp = interp;
553
554    /* Initialize GLUT here so it can parse and remove GLUT-specific
555     * command-line options before we parse the command-line below. */
556    glutInit(&argc, argv);
557    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
558    glutInitWindowSize(NanoVis::winWidth, NanoVis::winHeight);
559    glutInitWindowPosition(10, 10);
560    NanoVis::renderWindow = glutCreateWindow("nanovis");
561
562    glutIdleFunc(idle);
563    glutDisplayFunc(NanoVis::render);
564    glutReshapeFunc(reshape);
565
566    char *newResourcePath = NULL;
567    if (resourcePath == NULL) {
568        char *p;
569
570        // See if we can derive the path from the location of the program.
571        // Assume program is in the form <path>/bin/nanovis.
572        resourcePath = argv[0];
573        p = strrchr((char *)resourcePath, '/');
574        if (p != NULL) {
575            *p = '\0';
576            p = strrchr((char *)resourcePath, '/');
577        }
578        if (p == NULL) {
579            ERROR("Resource path not specified, and could not determine a valid path");
580            return 1;
581        }
582        *p = '\0';
583        newResourcePath = new char[(strlen(resourcePath) + 15) * 2 + 1];
584        sprintf(newResourcePath, "%s/lib/shaders:%s/lib/resources", resourcePath, resourcePath);
585        resourcePath = newResourcePath;
586        TRACE("No resource path specified, using: %s", resourcePath);
587    } else {
588        TRACE("Resource path: '%s'", resourcePath);
589    }
590
591    FilePath::getInstance()->setWorkingDirectory(argc, (const char**) argv);
592
593    if (!NanoVis::init(resourcePath)) {
594        exitService(1);
595    }
596    if (newResourcePath != NULL) {
597        delete [] newResourcePath;
598    }
599
600    Shader::init();
601    // Override callback with one that cleans up server on exit
602    Shader::setErrorCallback(shaderErrorCallback);
603
604    if (!NanoVis::initGL()) {
605        exitService(1);
606    }
607
608    if (!NanoVis::resizeOffscreenBuffer(NanoVis::winWidth, NanoVis::winHeight)) {
609        exitService(1);
610    }
611
612    glutMainLoop();
613
614    exitService(0);
615}
Note: See TracBrowser for help on using the repository browser.