source: vtkvis/trunk/RenderServer.cpp @ 4615

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

string fix

  • Property svn:eol-style set to native
File size: 17.2 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    int nBytes = oss.str().length();
206
207    TRACE("Sending OK for commands through %lu", g_stats.nCommands);
208#ifdef USE_THREADS
209    queueResponse(clientData, oss.str().c_str(), nBytes, Response::VOLATILE, Response::OK);
210#else
211    if (write(fdOut, oss.str().c_str(), nBytes) < 0) {
212        ERROR("write failed: %s", strerror(errno));
213        return -1;
214    }
215#endif
216    return 0;
217}
218
219int
220VtkVis::getStatsFile(Tcl_Interp *interp, Tcl_Obj *objPtr)
221{
222    Tcl_Obj **objv;
223    int objc;
224    int i;
225    char fileName[33];
226    md5_state_t state;
227    md5_byte_t digest[16];
228    char *string;
229    int length;
230
231    if ((objPtr == NULL) || (g_statsFile >= 0)) {
232        return g_statsFile;
233    }
234    if (Tcl_ListObjGetElements(interp, objPtr, &objc, &objv) != TCL_OK) {
235        return -1;
236    }
237    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("pid", 3));
238    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewIntObj(getpid()));
239    string = Tcl_GetStringFromObj(objPtr, &length);
240
241    md5_init(&state);
242    md5_append(&state, (const md5_byte_t *)string, length);
243    md5_finish(&state, digest);
244    for (i = 0; i < 16; i++) {
245        sprintf(fileName + i * 2, "%02x", digest[i]);
246    }
247    std::ostringstream oss;
248    oss << STATSDIR << "/" << fileName;
249    std::string pathStr = oss.str();
250
251    g_statsFile = open(pathStr.c_str(), O_EXCL | O_CREAT | O_WRONLY, 0600);
252    if (g_statsFile < 0) {
253        ERROR("can't open \"%s\": %s", pathStr.c_str(), strerror(errno));
254        return -1;
255    }
256    return g_statsFile;
257}
258
259int
260VtkVis::writeToStatsFile(int f, const char *s, size_t length)
261{
262    if (f >= 0) {
263        ssize_t numWritten;
264
265        numWritten = write(f, s, length);
266        if (numWritten == (ssize_t)length) {
267            close(dup(f));
268        }
269    }
270    return 0;
271}
272
273static int
274serverStats(int code)
275{
276    double start, finish;
277    char buf[BUFSIZ];
278    Tcl_DString ds;
279    int result;
280    int f;
281
282    {
283        struct timeval tv;
284
285        /* Get ending time.  */
286        gettimeofday(&tv, NULL);
287        finish = CVT2SECS(tv);
288        tv = g_stats.start;
289        start = CVT2SECS(tv);
290    }
291    /*
292     * Session information:
293     *   - Name of render server
294     *   - Process ID
295     *   - Hostname where server is running
296     *   - Start date of session
297     *   - Start date of session in seconds
298     *   - Number of data sets loaded from client
299     *   - Number of data bytes total loaded from client
300     *   - Number of frames returned
301     *   - Number of bytes total returned (in frames)
302     *   - Number of commands received
303     *   - Total elapsed time of all commands
304     *   - Total elapsed time of session
305     *   - Exit code of vizserver
306     *   - User time
307     *   - System time
308     *   - User time of children
309     *   - System time of children
310     */
311
312    Tcl_DStringInit(&ds);
313   
314    Tcl_DStringAppendElement(&ds, "render_stop");
315    /* renderer */
316    Tcl_DStringAppendElement(&ds, "renderer");
317    Tcl_DStringAppendElement(&ds, "vtkvis");
318    /* pid */
319    Tcl_DStringAppendElement(&ds, "pid");
320    sprintf(buf, "%d", getpid());
321    Tcl_DStringAppendElement(&ds, buf);
322    /* host */
323    Tcl_DStringAppendElement(&ds, "host");
324    gethostname(buf, BUFSIZ-1);
325    buf[BUFSIZ-1] = '\0';
326    Tcl_DStringAppendElement(&ds, buf);
327    /* date */
328    Tcl_DStringAppendElement(&ds, "date");
329    strcpy(buf, ctime(&g_stats.start.tv_sec));
330    buf[strlen(buf) - 1] = '\0';
331    Tcl_DStringAppendElement(&ds, buf);
332    /* date_secs */
333    Tcl_DStringAppendElement(&ds, "date_secs");
334    sprintf(buf, "%ld", g_stats.start.tv_sec);
335    Tcl_DStringAppendElement(&ds, buf);
336    /* num_data_sets */
337    Tcl_DStringAppendElement(&ds, "num_data_sets");
338    sprintf(buf, "%lu", (unsigned long int)g_stats.nDataSets);
339    Tcl_DStringAppendElement(&ds, buf);
340    /* data_set_bytes */
341    Tcl_DStringAppendElement(&ds, "data_set_bytes");
342    sprintf(buf, "%lu", (unsigned long int)g_stats.nDataBytes);
343    Tcl_DStringAppendElement(&ds, buf);
344    /* num_frames */
345    Tcl_DStringAppendElement(&ds, "num_frames");
346    sprintf(buf, "%lu", (unsigned long int)g_stats.nFrames);
347    Tcl_DStringAppendElement(&ds, buf);
348    /* frame_bytes */
349    Tcl_DStringAppendElement(&ds, "frame_bytes");
350    sprintf(buf, "%lu", (unsigned long int)g_stats.nFrameBytes);
351    Tcl_DStringAppendElement(&ds, buf);
352    /* num_commands */
353    Tcl_DStringAppendElement(&ds, "num_commands");
354    sprintf(buf, "%lu", (unsigned long int)g_stats.nCommands);
355    Tcl_DStringAppendElement(&ds, buf);
356    /* cmd_time */
357    Tcl_DStringAppendElement(&ds, "cmd_time");
358    sprintf(buf, "%g", g_stats.cmdTime);
359    Tcl_DStringAppendElement(&ds, buf);
360    /* session_time */
361    Tcl_DStringAppendElement(&ds, "session_time");
362    sprintf(buf, "%g", finish - start);
363    Tcl_DStringAppendElement(&ds, buf);
364    /* status */
365    Tcl_DStringAppendElement(&ds, "status");
366    sprintf(buf, "%d", code);
367    Tcl_DStringAppendElement(&ds, buf);
368    {
369        long clocksPerSec = sysconf(_SC_CLK_TCK);
370        double clockRes = 1.0 / clocksPerSec;
371        struct tms tms;
372
373        memset(&tms, 0, sizeof(tms));
374        times(&tms);
375        /* utime */
376        Tcl_DStringAppendElement(&ds, "utime");
377        sprintf(buf, "%g", tms.tms_utime * clockRes);
378        Tcl_DStringAppendElement(&ds, buf);
379        /* stime */
380        Tcl_DStringAppendElement(&ds, "stime");
381        sprintf(buf, "%g", tms.tms_stime * clockRes);
382        Tcl_DStringAppendElement(&ds, buf);
383        /* cutime */
384        Tcl_DStringAppendElement(&ds, "cutime");
385        sprintf(buf, "%g", tms.tms_cutime * clockRes);
386        Tcl_DStringAppendElement(&ds, buf);
387        /* cstime */
388        Tcl_DStringAppendElement(&ds, "cstime");
389        sprintf(buf, "%g", tms.tms_cstime * clockRes);
390        Tcl_DStringAppendElement(&ds, buf);
391    }
392    Tcl_DStringAppend(&ds, "\n", -1);
393    f = getStatsFile(NULL, NULL);
394    result = writeToStatsFile(f, Tcl_DStringValue(&ds),
395                              Tcl_DStringLength(&ds));
396    close(f);
397    Tcl_DStringFree(&ds);
398    return result;
399}
400
401static void
402initService()
403{
404    // Create a stream associated with the output file descriptor
405    g_fOut = fdopen(g_fdOut, "w");
406    // If running without a socket, use stdout for debugging
407    if (g_fOut == NULL && g_fdOut != STDOUT_FILENO) {
408        g_fdOut = STDOUT_FILENO;
409        g_fOut = stdout;
410    }
411
412    const char *user = getenv("USER");
413    char *logName = NULL;
414    int logNameLen = 0;
415
416    if (user == NULL) {
417        logNameLen = 19+1;
418        logName = (char *)calloc(logNameLen, sizeof(char));
419        strncpy(logName, "/tmp/vtkvis_log.txt", logNameLen);
420    }
421    else {
422        logNameLen = 16+strlen(user)+4+1;
423        logName = (char *)calloc(logNameLen, sizeof(char));
424        strncpy(logName, "/tmp/vtkvis_log_", logNameLen);
425        strncat(logName, user, strlen(user));
426        strncat(logName, ".txt", 4);
427    }
428
429    // open log and map stderr to log file
430    g_fLog = fopen(logName, "w");
431    dup2(fileno(g_fLog), STDERR_FILENO);
432    // If we are writing to socket, map stdout to log
433    if (g_fdOut != STDOUT_FILENO) {
434        dup2(fileno(g_fLog), STDOUT_FILENO);
435    }
436
437    fflush(stdout);
438
439    // clean up malloc'd memory
440    if (logName != NULL) {
441        free(logName);
442    }
443}
444
445static void
446exitService()
447{
448    serverStats(0);
449
450    // close log file
451    if (g_fLog != NULL) {
452        fclose(g_fLog);
453        g_fLog = NULL;
454    }
455}
456
457#ifdef USE_THREADS
458
459static void *
460writerThread(void *clientData)
461{
462    ResponseQueue *queue = (ResponseQueue *)clientData;
463
464    TRACE("Starting writer thread");
465    for (;;) {
466        Response *response = queue->dequeue();
467        if (response == NULL)
468            continue;
469        if (fwrite(response->message(), sizeof(unsigned char), response->length(),
470                   g_fOut) != response->length()) {
471            ERROR("short write while trying to write %ld bytes",
472                  response->length());
473        }
474        fflush(g_fOut);
475        TRACE("Wrote response of type %d", response->type());
476        delete response;
477        if (feof(g_fOut))
478            break;
479    }   
480    return NULL;
481}
482
483#endif  /*USE_THREADS*/
484
485int
486main(int argc, char *argv[])
487{
488    // Ignore SIGPIPE.  **Is this needed? **
489    signal(SIGPIPE, SIG_IGN);
490
491    while (1) {
492        int c = getopt(argc, argv, "i:o:");
493        if (c == -1) {
494            break;
495        }
496        switch (c) {
497        case 'i': {
498            int fd = atoi(optarg);
499            if (fd >=0 && fd < 5) {
500                g_fdIn = fd;
501            }
502        }
503            break;
504        case 'o': {
505            int fd = atoi(optarg);
506            if (fd >=0 && fd < 5) {
507                g_fdOut = fd;
508            }
509        }
510            break;
511        case '?':
512            break;
513        default:
514            return 1;
515        }
516    }
517
518    initService();
519    initLog();
520
521    memset(&g_stats, 0, sizeof(g_stats));
522    gettimeofday(&g_stats.start, NULL);
523
524    TRACE("Starting VTKVis Server");
525
526    // Sanity check: log descriptor can't be used for client IO
527    if (fileno(g_fLog) == g_fdIn) {
528        ERROR("Invalid input file descriptor");
529        return 1;
530    }
531    if (fileno(g_fLog) == g_fdOut) {
532        ERROR("Invalid output file descriptor");
533        return 1;
534    }
535    TRACE("File descriptors: in %d out %d log %d", g_fdIn, g_fdOut, fileno(g_fLog));
536
537#ifdef WANT_TRACE
538    vtksys::SystemInformation::SetStackTraceOnError(1);
539#endif
540
541    /* This synchronizes the client with the server, so that the client
542     * doesn't start writing commands before the server is ready. It could
543     * also be used to supply information about the server (version, memory
544     * size, etc). */
545    fprintf(g_fOut, "VtkVis %s (build %s)\n", VTKVIS_VERSION_STRING, SVN_VERSION);
546    fflush(g_fOut);
547
548    g_renderer = new Renderer();
549    g_inBufPtr = new ReadBuffer(g_fdIn, 1<<12);
550
551    Tcl_Interp *interp = Tcl_CreateInterp();
552    ClientData clientData = NULL;
553#ifdef USE_THREADS
554    ResponseQueue *queue = new ResponseQueue();
555    clientData = (ClientData)queue;
556    initTcl(interp, clientData);
557
558    pthread_t writerThreadId;
559    if (pthread_create(&writerThreadId, NULL, &writerThread, queue) < 0) {
560        ERROR("Can't create writer thread: %s", strerror(errno));
561    }
562#else
563    initTcl(interp, clientData);
564#endif
565
566    vtkSmartPointer<vtkUnsignedCharArray> imgData =
567        vtkSmartPointer<vtkUnsignedCharArray>::New();
568
569    // Start main server loop
570    for (;;) {
571        if (processCommands(interp, clientData, g_inBufPtr, g_fdOut) < 0)
572            break;
573
574        if (g_renderer->render()) {
575            TRACE("Rendering new frame");
576            g_renderer->getRenderedFrame(imgData);
577#ifdef USE_THREADS
578            queueFrame(queue, imgData);
579#else
580            writeFrame(g_fdOut, imgData);
581#endif
582            g_stats.nFrames++;
583            g_stats.nFrameBytes += imgData->GetDataSize() * imgData->GetDataTypeSize();
584        } else {
585            TRACE("No render required");
586            sendAck(clientData, g_fdOut);
587        }
588
589        if (g_inBufPtr->status() == ReadBuffer::ENDFILE)
590            break;
591    }
592#ifdef USE_THREADS
593    // Writer thread is probably blocked on sem_wait, so cancel instead
594    // of joining
595    if (pthread_cancel(writerThreadId) < 0) {
596        ERROR("Can't cancel writer thread: %s", strerror(errno));
597    } else {
598        TRACE("Cancelled writer thread");
599    }
600
601    TRACE("Deleting ResponseQueue");
602    delete queue;
603    queue = NULL;
604#endif
605
606    TRACE("Stopping Tcl interpreter");
607    exitTcl(interp);
608    interp = NULL;
609
610    TRACE("Deleting ReadBuffer");
611    delete g_inBufPtr;
612    g_inBufPtr = NULL;
613
614    TRACE("Deleting renderer");
615    delete g_renderer;
616    g_renderer = NULL;
617
618    TRACE("Exiting VTKVis Server");
619
620    closeLog();
621    exitService();
622
623    return 0;
624}
Note: See TracBrowser for help on using the repository browser.