source: nanovis/trunk/nanovisServer.cpp @ 4935

Last change on this file since 4935 was 4880, checked in by ldelgass, 9 years ago

Fix leak in sendDataToClient method (when USE_THREADS is enabled)

  • Property svn:eol-style set to native
File size: 16.2 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 "md5.h"
30
31#include "nanovis.h"
32#include "nanovisServer.h"
33#include "define.h"
34#include "Command.h"
35#include "PPMWriter.h"
36#include "ReadBuffer.h"
37#include "Shader.h"
38#ifdef USE_THREADS
39#include <pthread.h>
40#include "ResponseQueue.h"
41#endif
42#include "Trace.h"
43
44using namespace nv;
45using namespace nv::util;
46
47Stats nv::g_stats;
48int nv::g_statsFile = -1; ///< Stats output file descriptor.
49
50int nv::g_fdIn = STDIN_FILENO;     ///< Input file descriptor
51int nv::g_fdOut = STDOUT_FILENO;   ///< Output file descriptor
52FILE *nv::g_fOut = NULL;           ///< Output file handle
53FILE *nv::g_fLog = NULL;           ///< Trace logging file handle
54ReadBuffer *nv::g_inBufPtr = NULL; ///< Socket read buffer
55#ifdef USE_THREADS
56ResponseQueue *nv::g_queue = NULL;
57#endif
58
59#ifdef USE_THREADS
60
61static void
62queueFrame(ResponseQueue *queue, unsigned char *imgData)
63{
64    queuePPM(queue, "nv>image -type image -bytes",
65             imgData,
66             NanoVis::winWidth,
67             NanoVis::winHeight);
68}
69
70#else
71
72static void
73writeFrame(int fd, unsigned char *imgData)
74{
75    writePPM(fd, "nv>image -type image -bytes",
76             imgData,
77             NanoVis::winWidth,
78             NanoVis::winHeight);
79}
80
81#endif /*USE_THREADS*/
82
83static int
84sendAck()
85{
86    std::ostringstream oss;
87    oss << "nv>ok -token " << g_stats.nCommands <<  "\n";
88    std::string str = oss.str();
89    size_t numBytes = str.length();
90
91    TRACE("Sending OK for commands through %lu", g_stats.nCommands);
92#ifdef USE_THREADS
93    queueResponse(str.c_str(), numBytes, Response::VOLATILE, Response::OK);
94#else
95    if (write(g_fdOut, str.c_str(), numBytes) < 0) {
96        ERROR("write failed: %s", strerror(errno));
97        return -1;
98    }
99#endif
100    return 0;
101}
102
103#ifdef KEEPSTATS
104
105#ifndef STATSDIR
106#define STATSDIR        "/var/tmp/visservers"
107#endif  /*STATSDIR*/
108
109int
110nv::getStatsFile(Tcl_Obj *objPtr)
111{
112    Tcl_DString ds;
113    char fileName[33];
114    char pidstr[200];
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    /* By itself the client's key/value pairs aren't unique.  Add in the
125     * process id of this render server. */
126    sprintf(pidstr, "%ld", (long)g_stats.pid);
127
128    /* Create an md5 hash of the key/value pairs and use it as the file name. */
129    string = Tcl_GetStringFromObj(objPtr, &length);
130    md5_init(&state);
131    md5_append(&state, (const md5_byte_t *)string, strlen(string));
132    md5_append(&state, (const md5_byte_t *)pidstr, strlen(pidstr));
133    md5_finish(&state, digest);
134    for (int 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
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, "%ld", (long)g_stats.pid);
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)g_stats.nFrames);
229    Tcl_DStringAppendElement(&ds, buf);
230    /* frame_bytes */
231    Tcl_DStringAppendElement(&ds, "frame_bytes");
232    sprintf(buf, "%lu", (unsigned long)g_stats.nFrameBytes);
233    Tcl_DStringAppendElement(&ds, buf);
234    /* num_commands */
235    Tcl_DStringAppendElement(&ds, "num_commands");
236    sprintf(buf, "%lu", (unsigned long)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    int f = getStatsFile(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#endif
314    free(data);
315}
316
317static void
318initService()
319{
320    // Create a stream associated with the output file descriptor
321    g_fOut = fdopen(g_fdOut, "w");
322    // If running without a socket, use stdout for debugging
323    if (g_fOut == NULL) {
324        g_fdOut = STDOUT_FILENO;
325        g_fOut = stdout;
326    }
327
328    const char* user = getenv("USER");
329    char* logName = NULL;
330    int logNameLen = 0;
331
332    if (user == NULL) {
333        logNameLen = 20+1;
334        logName = (char *)calloc(logNameLen, sizeof(char));
335        strncpy(logName, "/tmp/nanovis_log.txt", logNameLen);
336    } else {
337        logNameLen = 17+1+strlen(user);
338        logName = (char *)calloc(logNameLen, sizeof(char));
339        strncpy(logName, "/tmp/nanovis_log_", logNameLen);
340        strncat(logName, user, strlen(user));
341    }
342
343    // open log and map stderr to log file
344    g_fLog = fopen(logName, "w");
345    dup2(fileno(g_fLog), STDERR_FILENO);
346    // If we are writing to socket, map stdout to log
347    if (g_fdOut != STDOUT_FILENO) {
348        dup2(fileno(g_fLog), STDOUT_FILENO);
349    }
350
351    fflush(stdout);
352
353    // clean up malloc'd memory
354    if (logName != NULL) {
355        free(logName);
356    }
357}
358
359static void
360exitService(int code)
361{
362    TRACE("Enter: %d", code);
363
364    NanoVis::removeAllData();
365
366    Shader::exit();
367
368    //close log file
369    if (g_fLog != NULL) {
370        fclose(g_fLog);
371        g_fLog = NULL;
372    }
373
374#ifdef KEEPSTATS
375    serverStats(code);
376#endif
377    closelog();
378
379    exit(code);
380}
381
382static void
383idle()
384{
385    TRACE("Enter");
386
387    glutSetWindow(NanoVis::renderWindow);
388
389    if (processCommands(NanoVis::interp, g_inBufPtr, g_fdOut) < 0) {
390        exitService(1);
391    }
392
393    NanoVis::update();
394    NanoVis::bindOffscreenBuffer();
395    NanoVis::render();
396    bool renderedSomething = true;
397    if (renderedSomething) {
398        TRACE("Rendering new frame");
399        NanoVis::readScreen();
400#ifdef USE_THREADS
401        queueFrame(g_queue, NanoVis::screenBuffer);
402#else
403        writeFrame(g_fdOut, NanoVis::screenBuffer);
404#endif
405        g_stats.nFrames++;
406        g_stats.nFrameBytes += NanoVis::winWidth * NanoVis::winHeight * 3;
407    } else {
408        TRACE("No render required");
409        sendAck();
410    }
411
412    if (g_inBufPtr->status() == ReadBuffer::ENDFILE) {
413        exitService(0);
414    }
415
416    TRACE("Leave");
417}
418
419#ifdef USE_THREADS
420
421static void *
422writerThread(void *clientData)
423{
424    ResponseQueue *queue = (ResponseQueue *)clientData;
425
426    TRACE("Starting writer thread");
427    for (;;) {
428        Response *response = queue->dequeue();
429        if (response == NULL)
430            continue;
431        if (fwrite(response->message(), sizeof(char), response->length(),
432                   g_fOut) != response->length()) {
433            ERROR("short write while trying to write %ld bytes",
434                  response->length());
435        }
436        fflush(g_fOut);
437        TRACE("Wrote response of type %d", response->type());
438        delete response;
439        if (feof(g_fOut))
440            break;
441    }   
442    return NULL;
443}
444
445#endif  /*USE_THREADS*/
446
447static
448void shaderErrorCallback(void)
449{
450    if (!Shader::printErrorInfo()) {
451        TRACE("Shader error, exiting...");
452        exitService(1);
453    }
454}
455
456static
457void reshape(int width, int height)
458{
459    NanoVis::resizeOffscreenBuffer(width, height);
460}
461
462int
463main(int argc, char **argv)
464{
465    // Ignore SIGPIPE.  **Is this needed? **
466    signal(SIGPIPE, SIG_IGN);
467
468    const char *resourcePath = NULL;
469    while (1) {
470        static struct option long_options[] = {
471            {"debug",   no_argument,       NULL, 'd'},
472            {"path",    required_argument, NULL, 'p'},
473            {0, 0, 0, 0}
474        };
475        int option_index = 0;
476        int c = getopt_long(argc, argv, "dp:i:o:", long_options, &option_index);
477        if (c == -1) {
478            break;
479        }
480        switch (c) {
481        case 'd':
482            NanoVis::debugFlag = true;
483            break;
484        case 'p':
485            resourcePath = optarg;
486            break;
487        case 'i': {
488            int fd = atoi(optarg);
489            if (fd >=0 && fd < 5) {
490                g_fdIn = fd;
491            }
492        }
493            break;
494        case 'o': {
495            int fd = atoi(optarg);
496            if (fd >=0 && fd < 5) {
497                g_fdOut = fd;
498            }
499        }
500            break;
501        case '?':
502            break;
503        default:
504            return 1;
505        }
506    }
507
508    initService();
509    initLog();
510
511    memset(&g_stats, 0, sizeof(g_stats));
512    g_stats.pid = getpid();
513    gettimeofday(&g_stats.start, NULL);
514
515    TRACE("Starting NanoVis Server");
516    if (NanoVis::debugFlag) {
517        TRACE("Debugging on");
518    }
519
520    // Sanity check: log descriptor can't be used for client IO
521    if (fileno(g_fLog) == g_fdIn) {
522        ERROR("Invalid input file descriptor");
523        return 1;
524    }
525    if (fileno(g_fLog) == g_fdOut) {
526        ERROR("Invalid output file descriptor");
527        return 1;
528    }
529    TRACE("File descriptors: in %d out %d log %d", g_fdIn, g_fdOut, fileno(g_fLog));
530
531    /* This synchronizes the client with the server, so that the client
532     * doesn't start writing commands before the server is ready. It could
533     * also be used to supply information about the server (version, memory
534     * size, etc). */
535    char mesg[200];
536
537    sprintf(mesg, "NanoVis %s (build %s)\n", NANOVIS_VERSION_STRING, SVN_VERSION);
538    size_t numBytes;
539    ssize_t numWritten;
540
541    numBytes = strlen(mesg);
542    numWritten = write(g_fdOut, mesg, numBytes);
543    if ((ssize_t)numBytes != numWritten) {
544        ERROR("Short write in version string: %s", strerror(errno));
545    }
546
547    g_inBufPtr = new ReadBuffer(g_fdIn, 1<<12);
548
549    Tcl_Interp *interp = Tcl_CreateInterp();
550    ClientData clientData = NULL;
551#ifdef USE_THREADS
552    g_queue = new ResponseQueue();
553    clientData = (ClientData)g_queue;
554    initTcl(interp, clientData);
555
556    pthread_t writerThreadId;
557    if (pthread_create(&writerThreadId, NULL, &writerThread, g_queue) < 0) {
558        ERROR("Can't create writer thread: %s", strerror(errno));
559    }
560#else
561    initTcl(interp, clientData);
562#endif
563    NanoVis::interp = interp;
564
565    /* Initialize GLUT here so it can parse and remove GLUT-specific
566     * command-line options before we parse the command-line below. */
567    glutInit(&argc, argv);
568    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
569    glutInitWindowSize(NanoVis::winWidth, NanoVis::winHeight);
570    glutInitWindowPosition(10, 10);
571    NanoVis::renderWindow = glutCreateWindow("nanovis");
572
573    glutIdleFunc(idle);
574    glutDisplayFunc(NanoVis::render);
575    glutReshapeFunc(reshape);
576
577    char *newResourcePath = NULL;
578    if (resourcePath == NULL) {
579        char *p;
580
581        // See if we can derive the path from the location of the program.
582        // Assume program is in the form <path>/bin/nanovis.
583        resourcePath = argv[0];
584        p = strrchr((char *)resourcePath, '/');
585        if (p != NULL) {
586            *p = '\0';
587            p = strrchr((char *)resourcePath, '/');
588        }
589        if (p == NULL) {
590            ERROR("Resource path not specified, and could not determine a valid path");
591            return 1;
592        }
593        *p = '\0';
594        newResourcePath = new char[(strlen(resourcePath) + 15) * 2 + 1];
595        sprintf(newResourcePath, "%s/lib/shaders:%s/lib/resources", resourcePath, resourcePath);
596        resourcePath = newResourcePath;
597        TRACE("No resource path specified, using: %s", resourcePath);
598    } else {
599        TRACE("Resource path: '%s'", resourcePath);
600    }
601
602    FilePath::getInstance()->setWorkingDirectory(argc, (const char**) argv);
603
604    if (!NanoVis::init(resourcePath)) {
605        exitService(1);
606    }
607    if (newResourcePath != NULL) {
608        delete [] newResourcePath;
609    }
610
611    Shader::init();
612    // Override callback with one that cleans up server on exit
613    Shader::setErrorCallback(shaderErrorCallback);
614
615    if (!NanoVis::initGL()) {
616        exitService(1);
617    }
618
619    if (!NanoVis::resizeOffscreenBuffer(NanoVis::winWidth, NanoVis::winHeight)) {
620        exitService(1);
621    }
622
623    glutMainLoop();
624
625    exitService(0);
626}
Note: See TracBrowser for help on using the repository browser.