source: vtkvis/branches/1.8/RenderServer.cpp @ 6607

Last change on this file since 6607 was 6607, checked in by ldelgass, 6 years ago

Fix missing acks (need to revisit processCommands return value)

  • Property svn:eol-style set to native
File size: 17.7 KB
Line 
1/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2/*
3 * Copyright (C) 2004-2012  HUBzero Foundation, LLC
4 *
5 * Author: Leif Delgass <ldelgass@purdue.edu>
6 */
7
8#include <cstdio>
9#include <cstring>
10#include <cstdlib>
11#include <cerrno>
12#include <unistd.h>
13#include <signal.h>
14#include <sys/types.h>
15#include <sys/stat.h>
16#include <fcntl.h>
17#include <sys/time.h>
18#include <sys/times.h>
19
20#include <string>
21#include <sstream>
22
23#include <tcl.h>
24
25#include <vtksys/SystemInformation.hxx>
26
27#include "Trace.h"
28#include "ReadBuffer.h"
29#include "RenderServer.h"
30#include "RendererCmd.h"
31#include "Renderer.h"
32#include "PPMWriter.h"
33#include "TGAWriter.h"
34#ifdef USE_THREADS
35#include <pthread.h>
36#include "ResponseQueue.h"
37#endif
38#include <md5.h>
39
40using namespace VtkVis;
41
42Stats VtkVis::g_stats;
43
44int VtkVis::g_statsFile = -1; ///< Stats output file descriptor.
45int VtkVis::g_fdIn = STDIN_FILENO; ///< Input file descriptor
46int VtkVis::g_fdOut = STDOUT_FILENO; ///< Output file descriptor
47FILE *VtkVis::g_fOut = NULL; ///< Output file handle
48FILE *VtkVis::g_fLog = NULL; ///< Trace logging file handle
49Renderer *VtkVis::g_renderer = NULL; ///< Main render worker
50ReadBuffer *VtkVis::g_inBufPtr = NULL; ///< Socket read buffer
51
52#ifdef USE_THREADS
53static void
54queueFrame(ResponseQueue *queue, vtkUnsignedCharArray *imgData)
55{
56#ifdef DEBUG
57    if (g_renderer->getCameraMode() == Renderer::IMAGE) {
58        double xywh[4];
59        g_renderer->getScreenWorldCoords(xywh);
60        TRACE("Image bbox: %g %g %g %g",
61              xywh[0],
62              (xywh[1] + xywh[3]),
63              (xywh[0] + xywh[2]),
64              xywh[1]);
65    }
66
67#ifdef RENDER_TARGA
68    writeTGAFile("/tmp/frame.tga",
69                 imgData->GetPointer(0),
70                 g_renderer->getWindowWidth(),
71                 g_renderer->getWindowHeight(),
72                 TARGA_BYTES_PER_PIXEL);
73#else
74    writeTGAFile("/tmp/frame.tga",
75                 imgData->GetPointer(0),
76                 g_renderer->getWindowWidth(),
77                 g_renderer->getWindowHeight(),
78                 TARGA_BYTES_PER_PIXEL,
79                 true);
80#endif  /*RENDER_TARGA*/
81
82#else
83    if (g_renderer->getCameraMode() == Renderer::IMAGE) {
84        double xywh[4];
85        g_renderer->getCameraZoomRegion(xywh);
86        std::ostringstream oss;
87        oss.precision(12);
88        // Send upper left and lower right corners as bbox
89        oss << "nv>image -type image -bbox {"
90            << std::scientific
91            << xywh[0] << " "
92            << xywh[1] << " "
93            << xywh[2] << " "
94            << xywh[3] << "} -bytes";
95
96#ifdef RENDER_TARGA
97        queueTGA(queue, oss.str().c_str(),
98                 imgData->GetPointer(0),
99                 g_renderer->getWindowWidth(),
100                 g_renderer->getWindowHeight(),
101                 TARGA_BYTES_PER_PIXEL);
102#else
103        queuePPM(queue, oss.str().c_str(),
104                 imgData->GetPointer(0),
105                 g_renderer->getWindowWidth(),
106                 g_renderer->getWindowHeight());
107#endif  /*RENDER_TARGA*/
108    } else {
109#ifdef RENDER_TARGA
110        queueTGA(queue, "nv>image -type image -bytes",
111                 imgData->GetPointer(0),
112                 g_renderer->getWindowWidth(),
113                 g_renderer->getWindowHeight(),
114                 TARGA_BYTES_PER_PIXEL);
115#else
116        queuePPM(queue, "nv>image -type image -bytes",
117                 imgData->GetPointer(0),
118                 g_renderer->getWindowWidth(),
119                 g_renderer->getWindowHeight());
120#endif  /*RENDER_TARGA*/
121    }
122#endif  /*DEBUG*/
123}
124
125#else
126
127static void
128writeFrame(int fd, vtkUnsignedCharArray *imgData)
129{
130#ifdef DEBUG
131    if (g_renderer->getCameraMode() == Renderer::IMAGE) {
132        double xywh[4];
133        g_renderer->getScreenWorldCoords(xywh);
134        TRACE("Image bbox: %g %g %g %g",
135              xywh[0],
136              (xywh[1] + xywh[3]),
137              (xywh[0] + xywh[2]),
138              xywh[1]);
139    }
140
141#ifdef RENDER_TARGA
142    writeTGAFile("/tmp/frame.tga",
143                 imgData->GetPointer(0),
144                 g_renderer->getWindowWidth(),
145                 g_renderer->getWindowHeight(),
146                 TARGA_BYTES_PER_PIXEL);
147#else
148    writeTGAFile("/tmp/frame.tga",
149                 imgData->GetPointer(0),
150                 g_renderer->getWindowWidth(),
151                 g_renderer->getWindowHeight(),
152                 TARGA_BYTES_PER_PIXEL,
153                 true);
154#endif  /*RENDER_TARGA*/
155
156#else
157    if (g_renderer->getCameraMode() == Renderer::IMAGE) {
158        double xywh[4];
159        g_renderer->getCameraZoomRegion(xywh);
160        std::ostringstream oss;
161        oss.precision(12);
162        // Send upper left and lower right corners as bbox
163        oss << "nv>image -type image -bbox {"
164            << std::scientific
165            << xywh[0] << " "
166            << xywh[1] << " "
167            << xywh[2] << " "
168            << xywh[3] << "} -bytes";
169
170#ifdef RENDER_TARGA
171        writeTGA(fd, oss.str().c_str(),
172                 imgData->GetPointer(0),
173                 g_renderer->getWindowWidth(),
174                 g_renderer->getWindowHeight(),
175                 TARGA_BYTES_PER_PIXEL);
176#else
177        writePPM(fd, oss.str().c_str(),
178                 imgData->GetPointer(0),
179                 g_renderer->getWindowWidth(),
180                 g_renderer->getWindowHeight());
181#endif  /*RENDER_TARGA*/
182    } else {
183#ifdef RENDER_TARGA
184        writeTGA(fd, "nv>image -type image -bytes",
185                 imgData->GetPointer(0),
186                 g_renderer->getWindowWidth(),
187                 g_renderer->getWindowHeight(),
188                 TARGA_BYTES_PER_PIXEL);
189#else
190        writePPM(fd, "nv>image -type image -bytes",
191                 imgData->GetPointer(0),
192                 g_renderer->getWindowWidth(),
193                 g_renderer->getWindowHeight());
194#endif  /*RENDER_TARGA*/
195    }
196#endif  /*DEBUG*/
197}
198#endif /*USE_THREADS*/
199
200static int
201sendAck(ClientData clientData, int fdOut)
202{
203    std::ostringstream oss;
204    oss << "nv>ok -token " << g_stats.nCommands <<  "\n";
205    std::string str = oss.str();
206    int nBytes = str.length();
207
208    TRACE("Sending OK for commands through %lu", g_stats.nCommands);
209#ifdef USE_THREADS
210    queueResponse(clientData, str.c_str(), nBytes, Response::VOLATILE, Response::OK);
211#else
212    if (write(fdOut, str.c_str(), nBytes) < 0) {
213        ERROR("write failed: %s", strerror(errno));
214        return -1;
215    }
216#endif
217    return 0;
218}
219
220int
221VtkVis::getStatsFile(Tcl_Obj *objPtr)
222{
223    char fileName[33];
224    char pidstr[200];
225    md5_state_t state;
226    md5_byte_t digest[16];
227    char *string;
228    int length;
229
230    if ((objPtr == NULL) || (g_statsFile >= 0)) {
231        return g_statsFile;
232    }
233    /* By itself the client's key/value pairs aren't unique.  Add in the
234     * process id of this render server. */
235    sprintf(pidstr, "%ld", (long)g_stats.pid);
236
237    /* Create an md5 hash of the key/value pairs and use it as the file name. */
238    string = Tcl_GetStringFromObj(objPtr, &length);
239    md5_init(&state);
240    md5_append(&state, (const md5_byte_t *)string, strlen(string));
241    md5_append(&state, (const md5_byte_t *)pidstr, strlen(pidstr));
242    md5_finish(&state, digest);
243    for (int i = 0; i < 16; i++) {
244        sprintf(fileName + i * 2, "%02x", digest[i]);
245    }
246    std::ostringstream oss;
247    oss << STATSDIR << "/" << fileName;
248    std::string pathStr = oss.str();
249
250    g_statsFile = open(pathStr.c_str(), O_EXCL | O_CREAT | O_WRONLY, 0600);
251    if (g_statsFile < 0) {
252        ERROR("can't open \"%s\": %s", pathStr.c_str(), strerror(errno));
253        return -1;
254    }
255    return g_statsFile;
256}
257
258int
259VtkVis::writeToStatsFile(int f, const char *s, size_t length)
260{
261    if (f >= 0) {
262        ssize_t numWritten;
263
264        numWritten = write(f, s, length);
265        if (numWritten == (ssize_t)length) {
266            close(dup(f));
267        }
268    }
269    return 0;
270}
271
272static int
273serverStats(int code)
274{
275    char buf[BUFSIZ];
276    Tcl_DString ds;
277    int result;
278
279    /* Get ending time.  */
280    struct timeval now;
281    gettimeofday(&now, NULL);
282    double session_time = CVT2SECS(now) - CVT2SECS(g_stats.start);
283
284    /*
285     * Session information:
286     *   - Name of render server
287     *   - Process ID
288     *   - Hostname where server is running
289     *   - Start date of session
290     *   - Start date of session in seconds
291     *   - Number of data sets loaded from client
292     *   - Number of data bytes total loaded from client
293     *   - Number of frames returned
294     *   - Number of bytes total returned (in frames)
295     *   - Number of commands received
296     *   - Total elapsed time of all commands
297     *   - Total elapsed time of session
298     *   - Exit code of vizserver
299     *   - User time
300     *   - System time
301     *   - User time of children
302     *   - System time of children
303     */
304
305    Tcl_DStringInit(&ds);
306   
307    Tcl_DStringAppendElement(&ds, "render_stop");
308    /* renderer */
309    Tcl_DStringAppendElement(&ds, "renderer");
310    Tcl_DStringAppendElement(&ds, "vtkvis");
311    /* pid */
312    Tcl_DStringAppendElement(&ds, "pid");
313    sprintf(buf, "%ld", (long)g_stats.pid);
314    Tcl_DStringAppendElement(&ds, buf);
315    /* host */
316    Tcl_DStringAppendElement(&ds, "host");
317    gethostname(buf, BUFSIZ-1);
318    buf[BUFSIZ-1] = '\0';
319    Tcl_DStringAppendElement(&ds, buf);
320    /* date */
321    Tcl_DStringAppendElement(&ds, "date");
322    strcpy(buf, ctime(&now.tv_sec));
323    buf[strlen(buf) - 1] = '\0';
324    Tcl_DStringAppendElement(&ds, buf);
325    /* date_secs */
326    Tcl_DStringAppendElement(&ds, "date_secs");
327    sprintf(buf, "%ld", now.tv_sec);
328    Tcl_DStringAppendElement(&ds, buf);
329    /* num_data_sets */
330    Tcl_DStringAppendElement(&ds, "num_data_sets");
331    sprintf(buf, "%lu", (unsigned long)g_stats.nDataSets);
332    Tcl_DStringAppendElement(&ds, buf);
333    /* data_set_bytes */
334    Tcl_DStringAppendElement(&ds, "data_set_bytes");
335    sprintf(buf, "%lu", (unsigned long)g_stats.nDataBytes);
336    Tcl_DStringAppendElement(&ds, buf);
337    /* num_frames */
338    Tcl_DStringAppendElement(&ds, "num_frames");
339    sprintf(buf, "%lu", (unsigned long)g_stats.nFrames);
340    Tcl_DStringAppendElement(&ds, buf);
341    /* frame_bytes */
342    Tcl_DStringAppendElement(&ds, "frame_bytes");
343    sprintf(buf, "%lu", (unsigned long)g_stats.nFrameBytes);
344    Tcl_DStringAppendElement(&ds, buf);
345    /* num_commands */
346    Tcl_DStringAppendElement(&ds, "num_commands");
347    sprintf(buf, "%lu", (unsigned long)g_stats.nCommands);
348    Tcl_DStringAppendElement(&ds, buf);
349    /* cmd_time */
350    Tcl_DStringAppendElement(&ds, "cmd_time");
351    sprintf(buf, "%g", g_stats.cmdTime);
352    Tcl_DStringAppendElement(&ds, buf);
353    /* session_time */
354    Tcl_DStringAppendElement(&ds, "session_time");
355    sprintf(buf, "%g", session_time);
356    Tcl_DStringAppendElement(&ds, buf);
357    /* status */
358    Tcl_DStringAppendElement(&ds, "status");
359    sprintf(buf, "%d", code);
360    Tcl_DStringAppendElement(&ds, buf);
361    {
362        long clocksPerSec = sysconf(_SC_CLK_TCK);
363        double clockRes = 1.0 / clocksPerSec;
364        struct tms tms;
365
366        memset(&tms, 0, sizeof(tms));
367        times(&tms);
368        /* utime */
369        Tcl_DStringAppendElement(&ds, "utime");
370        sprintf(buf, "%g", tms.tms_utime * clockRes);
371        Tcl_DStringAppendElement(&ds, buf);
372        /* stime */
373        Tcl_DStringAppendElement(&ds, "stime");
374        sprintf(buf, "%g", tms.tms_stime * clockRes);
375        Tcl_DStringAppendElement(&ds, buf);
376        /* cutime */
377        Tcl_DStringAppendElement(&ds, "cutime");
378        sprintf(buf, "%g", tms.tms_cutime * clockRes);
379        Tcl_DStringAppendElement(&ds, buf);
380        /* cstime */
381        Tcl_DStringAppendElement(&ds, "cstime");
382        sprintf(buf, "%g", tms.tms_cstime * clockRes);
383        Tcl_DStringAppendElement(&ds, buf);
384    }
385    Tcl_DStringAppend(&ds, "\n", -1);
386    int fd = getStatsFile(NULL);
387    result = writeToStatsFile(fd, Tcl_DStringValue(&ds),
388                              Tcl_DStringLength(&ds));
389    close(fd);
390    Tcl_DStringFree(&ds);
391    return result;
392}
393
394static void
395initService()
396{
397    // Create a stream associated with the output file descriptor
398    g_fOut = fdopen(g_fdOut, "w");
399    // If running without a socket, use stdout for debugging
400    if (g_fOut == NULL && g_fdOut != STDOUT_FILENO) {
401        g_fdOut = STDOUT_FILENO;
402        g_fOut = stdout;
403    }
404
405    const char *user = getenv("USER");
406    char *logName = NULL;
407    int logNameLen = 0;
408
409    if (user == NULL) {
410        logNameLen = 19+1;
411        logName = (char *)calloc(logNameLen, sizeof(char));
412        strncpy(logName, "/tmp/vtkvis_log.txt", logNameLen);
413    }
414    else {
415        logNameLen = 16+strlen(user)+4+1;
416        logName = (char *)calloc(logNameLen, sizeof(char));
417        strncpy(logName, "/tmp/vtkvis_log_", logNameLen);
418        strncat(logName, user, strlen(user));
419        strncat(logName, ".txt", 4);
420    }
421
422    // open log and map stderr to log file
423    g_fLog = fopen(logName, "w");
424    dup2(fileno(g_fLog), STDERR_FILENO);
425    // If we are writing to socket, map stdout to log
426    if (g_fdOut != STDOUT_FILENO) {
427        dup2(fileno(g_fLog), STDOUT_FILENO);
428    }
429
430    fflush(stdout);
431
432    // clean up malloc'd memory
433    if (logName != NULL) {
434        free(logName);
435    }
436}
437
438static void
439exitService()
440{
441    serverStats(0);
442
443    // close log file
444    if (g_fLog != NULL) {
445        fclose(g_fLog);
446        g_fLog = NULL;
447    }
448}
449
450#ifdef USE_THREADS
451
452static void *
453writerThread(void *clientData)
454{
455    ResponseQueue *queue = (ResponseQueue *)clientData;
456
457    TRACE("Starting writer thread");
458    for (;;) {
459        Response *response = queue->dequeue();
460        if (response == NULL)
461            continue;
462        if (fwrite(response->message(), sizeof(unsigned char), response->length(),
463                   g_fOut) != response->length()) {
464            ERROR("short write while trying to write %ld bytes",
465                  response->length());
466        }
467        fflush(g_fOut);
468        TRACE("Wrote response of type %d", response->type());
469        delete response;
470        if (feof(g_fOut))
471            break;
472    }   
473    return NULL;
474}
475
476#endif  /*USE_THREADS*/
477
478int
479main(int argc, char *argv[])
480{
481    // Ignore SIGPIPE.  **Is this needed? **
482    signal(SIGPIPE, SIG_IGN);
483
484    long idleTimeout = -1L;
485    while (1) {
486        int c = getopt(argc, argv, "i:o:t:");
487        if (c == -1) {
488            break;
489        }
490        switch (c) {
491        case 'i': {
492            int fd = atoi(optarg);
493            if (fd >=0 && fd < 5) {
494                g_fdIn = fd;
495            }
496        }
497            break;
498        case 'o': {
499            int fd = atoi(optarg);
500            if (fd >=0 && fd < 5) {
501                g_fdOut = fd;
502            }
503        }
504            break;
505        case 't':
506            // Idle timeout in seconds
507            idleTimeout = atol(optarg);
508            break;
509        case '?':
510            break;
511        default:
512            return 1;
513        }
514    }
515
516    initService();
517    initLog();
518
519    memset(&g_stats, 0, sizeof(g_stats));
520    g_stats.pid = getpid();
521    gettimeofday(&g_stats.start, NULL);
522
523    TRACE("Starting VTKVis Server");
524
525    // Sanity check: log descriptor can't be used for client IO
526    if (fileno(g_fLog) == g_fdIn) {
527        ERROR("Invalid input file descriptor");
528        return 1;
529    }
530    if (fileno(g_fLog) == g_fdOut) {
531        ERROR("Invalid output file descriptor");
532        return 1;
533    }
534    TRACE("File descriptors: in %d out %d log %d", g_fdIn, g_fdOut, fileno(g_fLog));
535
536#ifdef WANT_TRACE
537    vtksys::SystemInformation::SetStackTraceOnError(1);
538#endif
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, "VtkVis %s (build %s)\n", VTKVIS_VERSION_STRING, SVN_VERSION);
545    fflush(g_fOut);
546
547    g_renderer = new Renderer();
548    g_inBufPtr = new ReadBuffer(g_fdIn, 1<<12);
549
550    g_renderer->setIdleTimeout(idleTimeout);
551
552    Tcl_Interp *interp = Tcl_CreateInterp();
553    ClientData clientData = NULL;
554#ifdef USE_THREADS
555    ResponseQueue *queue = new ResponseQueue();
556    clientData = (ClientData)queue;
557    initTcl(interp, clientData);
558
559    pthread_t writerThreadId;
560    if (pthread_create(&writerThreadId, NULL, &writerThread, queue) < 0) {
561        ERROR("Can't create writer thread: %s", strerror(errno));
562    }
563#else
564    initTcl(interp, clientData);
565#endif
566
567    vtkSmartPointer<vtkUnsignedCharArray> imgData =
568        vtkSmartPointer<vtkUnsignedCharArray>::New();
569
570    // Start main server loop
571    for (;;) {
572        struct timeval timeout;
573        g_renderer->getTimeout(&timeout);
574        int cmdStatus = processCommands(interp, clientData, g_inBufPtr, g_fdOut, &timeout);
575        if (cmdStatus < 0)
576            break;
577
578        if (g_renderer->render()) {
579            TRACE("Rendering new frame");
580            g_renderer->getRenderedFrame(imgData);
581#ifdef USE_THREADS
582            queueFrame(queue, imgData);
583#else
584            writeFrame(g_fdOut, imgData);
585#endif
586            g_stats.nFrames++;
587            g_stats.nFrameBytes += imgData->GetDataSize() * imgData->GetDataTypeSize();
588        } else {
589            TRACE("No render required (status = %d)", cmdStatus);
590            sendAck(clientData, g_fdOut);
591        }
592
593        if (g_inBufPtr->status() == ReadBuffer::ENDFILE)
594            break;
595    }
596#ifdef USE_THREADS
597    // Writer thread is probably blocked on sem_wait, so cancel instead
598    // of joining
599    if (pthread_cancel(writerThreadId) < 0) {
600        ERROR("Can't cancel writer thread: %s", strerror(errno));
601    } else {
602        TRACE("Cancelled writer thread");
603    }
604
605    TRACE("Deleting ResponseQueue");
606    delete queue;
607    queue = NULL;
608#endif
609
610    TRACE("Stopping Tcl interpreter");
611    exitTcl(interp);
612    interp = NULL;
613
614    TRACE("Deleting ReadBuffer");
615    delete g_inBufPtr;
616    g_inBufPtr = NULL;
617
618    TRACE("Deleting renderer");
619    delete g_renderer;
620    g_renderer = NULL;
621
622    TRACE("Exiting VTKVis Server");
623
624    closeLog();
625    exitService();
626
627    return 0;
628}
Note: See TracBrowser for help on using the repository browser.