source: nanovis/trunk/nanovisServer.cpp @ 4823

Last change on this file since 4823 was 4823, checked in by ldelgass, 7 years ago

minor fixes to sync

  • 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    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, "%ld", (long)g_stats.pid);
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)g_stats.nFrames);
230    Tcl_DStringAppendElement(&ds, buf);
231    /* frame_bytes */
232    Tcl_DStringAppendElement(&ds, "frame_bytes");
233    sprintf(buf, "%lu", (unsigned long)g_stats.nFrameBytes);
234    Tcl_DStringAppendElement(&ds, buf);
235    /* num_commands */
236    Tcl_DStringAppendElement(&ds, "num_commands");
237    sprintf(buf, "%lu", (unsigned long)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);
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    // Create a stream associated with the output file descriptor
322    g_fOut = fdopen(g_fdOut, "w");
323    // If running without a socket, use stdout for debugging
324    if (g_fOut == NULL) {
325        g_fdOut = STDOUT_FILENO;
326        g_fOut = stdout;
327    }
328
329    const char* user = getenv("USER");
330    char* logName = NULL;
331    int logNameLen = 0;
332
333    if (user == NULL) {
334        logNameLen = 20+1;
335        logName = (char *)calloc(logNameLen, sizeof(char));
336        strncpy(logName, "/tmp/nanovis_log.txt", logNameLen);
337    } else {
338        logNameLen = 17+1+strlen(user);
339        logName = (char *)calloc(logNameLen, sizeof(char));
340        strncpy(logName, "/tmp/nanovis_log_", logNameLen);
341        strncat(logName, user, strlen(user));
342    }
343
344    // open log and map stderr to log file
345    g_fLog = fopen(logName, "w");
346    dup2(fileno(g_fLog), STDERR_FILENO);
347    // If we are writing to socket, map stdout to log
348    if (g_fdOut != STDOUT_FILENO) {
349        dup2(fileno(g_fLog), STDOUT_FILENO);
350    }
351
352    fflush(stdout);
353
354    // clean up malloc'd memory
355    if (logName != NULL) {
356        free(logName);
357    }
358}
359
360static void
361exitService(int code)
362{
363    TRACE("Enter: %d", code);
364
365    NanoVis::removeAllData();
366
367    Shader::exit();
368
369    //close log file
370    if (g_fLog != NULL) {
371        fclose(g_fLog);
372        g_fLog = NULL;
373    }
374
375#ifdef KEEPSTATS
376    serverStats(code);
377#endif
378    closelog();
379
380    exit(code);
381}
382
383static void
384idle()
385{
386    TRACE("Enter");
387
388    glutSetWindow(NanoVis::renderWindow);
389
390    if (processCommands(NanoVis::interp, g_inBufPtr, g_fdOut) < 0) {
391        exitService(1);
392    }
393
394    NanoVis::update();
395    NanoVis::bindOffscreenBuffer();
396    NanoVis::render();
397    bool renderedSomething = true;
398    if (renderedSomething) {
399        TRACE("Rendering new frame");
400        NanoVis::readScreen();
401#ifdef USE_THREADS
402        queueFrame(g_queue, NanoVis::screenBuffer);
403#else
404        writeFrame(g_fdOut, NanoVis::screenBuffer);
405#endif
406        g_stats.nFrames++;
407        g_stats.nFrameBytes += NanoVis::winWidth * NanoVis::winHeight * 3;
408    } else {
409        TRACE("No render required");
410        sendAck();
411    }
412
413    if (g_inBufPtr->status() == ReadBuffer::ENDFILE) {
414        exitService(0);
415    }
416
417    TRACE("Leave");
418}
419
420#ifdef USE_THREADS
421
422static void *
423writerThread(void *clientData)
424{
425    ResponseQueue *queue = (ResponseQueue *)clientData;
426
427    TRACE("Starting writer thread");
428    for (;;) {
429        Response *response = queue->dequeue();
430        if (response == NULL)
431            continue;
432        if (fwrite(response->message(), sizeof(char), response->length(),
433                   g_fOut) != response->length()) {
434            ERROR("short write while trying to write %ld bytes",
435                  response->length());
436        }
437        fflush(g_fOut);
438        TRACE("Wrote response of type %d", response->type());
439        delete response;
440        if (feof(g_fOut))
441            break;
442    }   
443    return NULL;
444}
445
446#endif  /*USE_THREADS*/
447
448static
449void shaderErrorCallback(void)
450{
451    if (!Shader::printErrorInfo()) {
452        TRACE("Shader error, exiting...");
453        exitService(1);
454    }
455}
456
457static
458void reshape(int width, int height)
459{
460    NanoVis::resizeOffscreenBuffer(width, height);
461}
462
463int
464main(int argc, char **argv)
465{
466    // Ignore SIGPIPE.  **Is this needed? **
467    signal(SIGPIPE, SIG_IGN);
468
469    const char *resourcePath = NULL;
470    while (1) {
471        static struct option long_options[] = {
472            {"debug",   no_argument,       NULL, 'd'},
473            {"path",    required_argument, NULL, 'p'},
474            {0, 0, 0, 0}
475        };
476        int option_index = 0;
477        int c = getopt_long(argc, argv, "dp:i:o:", long_options, &option_index);
478        if (c == -1) {
479            break;
480        }
481        switch (c) {
482        case 'd':
483            NanoVis::debugFlag = true;
484            break;
485        case 'p':
486            resourcePath = optarg;
487            break;
488        case 'i': {
489            int fd = atoi(optarg);
490            if (fd >=0 && fd < 5) {
491                g_fdIn = fd;
492            }
493        }
494            break;
495        case 'o': {
496            int fd = atoi(optarg);
497            if (fd >=0 && fd < 5) {
498                g_fdOut = fd;
499            }
500        }
501            break;
502        case '?':
503            break;
504        default:
505            return 1;
506        }
507    }
508
509    initService();
510    initLog();
511
512    memset(&g_stats, 0, sizeof(g_stats));
513    g_stats.pid = getpid();
514    gettimeofday(&g_stats.start, NULL);
515
516    TRACE("Starting NanoVis Server");
517    if (NanoVis::debugFlag) {
518        TRACE("Debugging on");
519    }
520
521    // Sanity check: log descriptor can't be used for client IO
522    if (fileno(g_fLog) == g_fdIn) {
523        ERROR("Invalid input file descriptor");
524        return 1;
525    }
526    if (fileno(g_fLog) == g_fdOut) {
527        ERROR("Invalid output file descriptor");
528        return 1;
529    }
530    TRACE("File descriptors: in %d out %d log %d", g_fdIn, g_fdOut, fileno(g_fLog));
531
532    /* This synchronizes the client with the server, so that the client
533     * doesn't start writing commands before the server is ready. It could
534     * also be used to supply information about the server (version, memory
535     * size, etc). */
536    char mesg[200];
537
538    sprintf(mesg, "NanoVis %s (build %s)\n", NANOVIS_VERSION_STRING, SVN_VERSION);
539    size_t numBytes;
540    ssize_t numWritten;
541
542    numBytes = strlen(mesg);
543    numWritten = write(g_fdOut, mesg, numBytes);
544    if ((ssize_t)numBytes != numWritten) {
545        ERROR("Short write in version string: %s", strerror(errno));
546    }
547
548    g_inBufPtr = new ReadBuffer(g_fdIn, 1<<12);
549
550    Tcl_Interp *interp = Tcl_CreateInterp();
551    ClientData clientData = NULL;
552#ifdef USE_THREADS
553    g_queue = new ResponseQueue();
554    clientData = (ClientData)g_queue;
555    initTcl(interp, clientData);
556
557    pthread_t writerThreadId;
558    if (pthread_create(&writerThreadId, NULL, &writerThread, g_queue) < 0) {
559        ERROR("Can't create writer thread: %s", strerror(errno));
560    }
561#else
562    initTcl(interp, clientData);
563#endif
564    NanoVis::interp = interp;
565
566    /* Initialize GLUT here so it can parse and remove GLUT-specific
567     * command-line options before we parse the command-line below. */
568    glutInit(&argc, argv);
569    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
570    glutInitWindowSize(NanoVis::winWidth, NanoVis::winHeight);
571    glutInitWindowPosition(10, 10);
572    NanoVis::renderWindow = glutCreateWindow("nanovis");
573
574    glutIdleFunc(idle);
575    glutDisplayFunc(NanoVis::render);
576    glutReshapeFunc(reshape);
577
578    char *newResourcePath = NULL;
579    if (resourcePath == NULL) {
580        char *p;
581
582        // See if we can derive the path from the location of the program.
583        // Assume program is in the form <path>/bin/nanovis.
584        resourcePath = argv[0];
585        p = strrchr((char *)resourcePath, '/');
586        if (p != NULL) {
587            *p = '\0';
588            p = strrchr((char *)resourcePath, '/');
589        }
590        if (p == NULL) {
591            ERROR("Resource path not specified, and could not determine a valid path");
592            return 1;
593        }
594        *p = '\0';
595        newResourcePath = new char[(strlen(resourcePath) + 15) * 2 + 1];
596        sprintf(newResourcePath, "%s/lib/shaders:%s/lib/resources", resourcePath, resourcePath);
597        resourcePath = newResourcePath;
598        TRACE("No resource path specified, using: %s", resourcePath);
599    } else {
600        TRACE("Resource path: '%s'", resourcePath);
601    }
602
603    FilePath::getInstance()->setWorkingDirectory(argc, (const char**) argv);
604
605    if (!NanoVis::init(resourcePath)) {
606        exitService(1);
607    }
608    if (newResourcePath != NULL) {
609        delete [] newResourcePath;
610    }
611
612    Shader::init();
613    // Override callback with one that cleans up server on exit
614    Shader::setErrorCallback(shaderErrorCallback);
615
616    if (!NanoVis::initGL()) {
617        exitService(1);
618    }
619
620    if (!NanoVis::resizeOffscreenBuffer(NanoVis::winWidth, NanoVis::winHeight)) {
621        exitService(1);
622    }
623
624    glutMainLoop();
625
626    exitService(0);
627}
Note: See TracBrowser for help on using the repository browser.