source: nanovis/branches/1.2/nanovisServer.cpp @ 6395

Last change on this file since 6395 was 6395, checked in by ldelgass, 8 years ago

merge r6394 from nanovis trunk

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