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

Last change on this file since 4063 was 4063, checked in by ldelgass, 10 years ago

Remove some more Rappture deps from nanovis

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