Buffer.C 16.2 KB
Newer Older
1 2
/*****************************************************************************
*
3
* Copyright (c) 2000 - 2013, Lawrence Livermore National Security, LLC
4
* Produced at the Lawrence Livermore National Laboratory
5
* LLNL-CODE-442911
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
* All rights reserved.
*
* This file is  part of VisIt. For  details, see https://visit.llnl.gov/.  The
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution  and  use  in  source  and  binary  forms,  with  or  without
* modification, are permitted provided that the following conditions are met:
*
*  - Redistributions of  source code must  retain the above  copyright notice,
*    this list of conditions and the disclaimer below.
*  - Redistributions in binary form must reproduce the above copyright notice,
*    this  list of  conditions  and  the  disclaimer (as noted below)  in  the
*    documentation and/or other materials provided with the distribution.
*  - Neither the name of  the LLNS/LLNL nor the names of  its contributors may
*    be used to endorse or promote products derived from this software without
*    specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT  HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR  IMPLIED WARRANTIES, INCLUDING,  BUT NOT  LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND  FITNESS FOR A PARTICULAR  PURPOSE
* ARE  DISCLAIMED. IN  NO EVENT  SHALL LAWRENCE  LIVERMORE NATIONAL  SECURITY,
* LLC, THE  U.S.  DEPARTMENT OF  ENERGY  OR  CONTRIBUTORS BE  LIABLE  FOR  ANY
* DIRECT,  INDIRECT,   INCIDENTAL,   SPECIAL,   EXEMPLARY,  OR   CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT  LIMITED TO, PROCUREMENT OF  SUBSTITUTE GOODS OR
* SERVICES; LOSS OF  USE, DATA, OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER
* CAUSED  AND  ON  ANY  THEORY  OF  LIABILITY,  WHETHER  IN  CONTRACT,  STRICT
* LIABILITY, OR TORT  (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY  WAY
* OUT OF THE  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*****************************************************************************/

#include "Buffer.h"

#include <string>
#include <sstream>
#include <iostream>

using namespace std;

PyObject *Buffer::pickleModule = NULL;
PyObject *Buffer::pickleDict  = NULL;
PyObject *Buffer::pickleDumps = NULL;
PyObject *Buffer::pickleLoads = NULL;

/*****************************************************************************
 * Function: Buffer Constructor
 *
 * Purpose: 
 *   Creates an empty mpi buffer.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Wed Jan  7 10:05:02 PST 2009
 *
 * Modifications:
 *
 * ***************************************************************************/

Buffer::Buffer()
: alloced(false), size(0), buffer(NULL), data(NULL)
{
    Reset();
}

/*****************************************************************************
 * Function: Buffer Constructor
 *
 * Purpose:
 *   Wraps a pointer to an existing buffer.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Wed Jan  7 10:05:02 PST 2009
 *
 * Modifications:
 *
 * ***************************************************************************/

Buffer::Buffer(void *buff_ptr)
: alloced(false), size(0), buffer(NULL), data(NULL)
{
    Init(buff_ptr);
}

/*****************************************************************************
 * Function: Buffer Constructor
 *
 * Purpose:
 *   Creates an mpi buffer of given total size.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Wed Jan  7 10:05:02 PST 2009
 *
 * Modifications:
 *
 * ***************************************************************************/

Buffer::Buffer(int buffer_size)
: alloced(false), size(0), buffer(NULL), data(NULL)
{
    Init(buffer_size);
}

/*****************************************************************************
 * Function: Buffer Constructor
 *
 * Purpose: 
 *   Creates an mpi buffer of given type and size.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Wed Jan  7 10:05:02 PST 2009
 *
 * Modifications:
 *
 * ***************************************************************************/

Buffer::Buffer(int type_id, int data_size)
: alloced(false), size(0), buffer(NULL), data(NULL)
{
    Init(type_id,data_size);
}

/*****************************************************************************
 * Function: Buffer Constructor
 *
 * Purpose:
 *   Creates an mpi buffer from a python object.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Wed Jan  7 10:05:02 PST 2009
 *
 * Modifications:
 *
 * ***************************************************************************/

Buffer::Buffer(PyObject *py_obj)
: alloced(false), size(0), buffer(NULL), data(NULL)
{
    Init(py_obj);
}


/*****************************************************************************
 * Function: Buffer Destructor
 *
 * Purpose: 
 *   Destroys an mpi buffer.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Wed Jan  7 10:05:02 PST 2009
 *
 * Modifications:
 *
 * ***************************************************************************/

Buffer::~Buffer()
{
    Reset();
}

/*****************************************************************************
 * Function: Buffer::Init
 *
 * Purpose:
 *   Inits buffer to given size.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Wed Jan  7 10:05:02 PST 2009
 *
 * Modifications:
 *
 * ***************************************************************************/

void
Buffer::Init(void *buff_ptr)
{
    if(BufferSize() > 0)
        Reset();

    alloced = false;

    buffer = buff_ptr;
    data = (void*)(((char*)buffer) + 2 * sizeof(int));

    int *header_ptr = HeaderPtr();
    // get type & data size to calc the full buffer size.
    int type_id   = header_ptr[0];
    int data_size = header_ptr[1];

    this->size = TotalBufferSize(type_id,data_size);
}


/*****************************************************************************
 * Function: Buffer::Init
 *
 * Purpose:
 *   Inits buffer to given size.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Wed Jan  7 10:05:02 PST 2009
 *
 * Modifications:
209
 *  Guard against invalid buffer sizes.
210 211 212 213 214 215 216 217 218
 *
 * ***************************************************************************/

void
Buffer::Init(int buffer_size)
{
    if(BufferSize() > 0)
        Reset();

219
    // Any buffer size smaller than the header is invalid.
220
    if((size_t)buffer_size >= (2 * sizeof(int) ))
221 222 223 224 225 226 227 228 229
    {
        this->size = buffer_size;
        buffer = (void*) new char[this->size];
        int *header_ptr = HeaderPtr();
        header_ptr[0] = EMPTY;
        header_ptr[1] = 0;
        data = (void*)(((char*)buffer) + 2 * sizeof(int));
        alloced = true;
    }
230 231 232 233 234
}

/*****************************************************************************
 * Function: Buffer::Init
 *
235
 * Purpose:
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
 *   Inits buffer to given type and size.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Wed Jan  7 10:05:02 PST 2009
 *
 * Modifications:
 *
 * ***************************************************************************/

void
Buffer::Init(int type_id, int data_size)
{
    if(BufferSize() > 0)
        Reset();

    if(data_size == 0)
        return;

    int header_size = 2 * sizeof(int);
    this->size = TotalBufferSize(type_id,data_size);

    buffer = (void*) new char[this->size];
    int *header_ptr = HeaderPtr();
    header_ptr[0] = type_id;
    header_ptr[1] = data_size;
    data = (void*)(((char*)buffer) + header_size);
    alloced = true;
}


/*****************************************************************************
 * Function: Buffer::Init
 *
 * Purpose: 
 *   Inits buffer from a python object.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Wed Jan  7 10:05:02 PST 2009
 *
 * Modifications:
276 277 278
 *   Cyrus Harrison, Fri Jul  9 10:31:03 PDT 2010
 *   Use pickle to encode empty python sequences & use faster
 *   PyObject_CallFunctionObjArgs() instead of PyObject_CallFunction().
279
 *
280 281 282
 *   Cyrus Harrison, Tue Oct 11 10:48:06 PDT 2011
 *   Use long instead of int.
 * 
283 284 285 286 287 288 289 290
 * ***************************************************************************/
void
Buffer::Init(PyObject *py_obj)
{
    bool pickle = false;

    if(py_obj == NULL)
        Reset();
291
    else if(PyInt_CheckExact(py_obj))
292 293 294 295
    {
        Init(INTEGER,1);
        DataAsIntPtr()[0] = PyInt_AS_LONG(py_obj);
    }
296 297 298 299 300
    else if(PyLong_CheckExact(py_obj))
    {
        Init(INTEGER,1);
        DataAsIntPtr()[0] = PyLong_AsLong(py_obj);
    }
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    else if(PyFloat_Check(py_obj))
    {
        Init(DOUBLE,1);
        DataAsDoublePtr()[0] = PyFloat_AS_DOUBLE(py_obj);
    }
    else if(PyString_Check(py_obj))
    {
        char *py_data = PyString_AS_STRING(py_obj);
        int slen = strlen(py_data) +1;
        Init(STRING,slen);
        char *ptr = DataAsCharPtr();
        memset(ptr,0,slen*sizeof(char));
        memcpy(ptr,py_data,(slen-1)*sizeof(char));
    }
    else if(PySequence_Check(py_obj))
    {
        PyObject *py_seq  = PySequence_Fast(py_obj,"Expected Sequence");
        int length = PySequence_Size(py_seq);

320 321 322 323
        // if we have an empty sequence let pickle take care of it.
        if(length == 0)
            pickle=true;

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
        // check for list type all numeric entries 
        for(int i=0; i < length && !pickle; i++)
        {
            PyObject *py_itm = PySequence_Fast_GET_ITEM(py_seq,i); // borrowed
            if(!PyNumber_Check(py_itm))
                pickle = true;
        }

        if(!pickle)
        {
            Init(DOUBLE,length);
            double *ptr = DataAsDoublePtr();
            for(int i=0; i < length; i++)
            {
                PyObject *py_itm = PySequence_Fast_GET_ITEM(py_seq,i); // borrowed
                PyObject *py_val = PyNumber_Float(py_itm);
                ptr[i] = PyFloat_AS_DOUBLE(py_val);
                Py_DECREF(py_val);
            }
        }
        Py_DECREF(py_seq);
    }
    else
        pickle =true;

    if(pickle)
    {
351 352 353 354 355
        PyObject *res = PyObject_CallFunctionObjArgs(pickleDumps,py_obj,NULL);
        // This case should't occur, but print an error msg just in case.
        if(res == NULL || PyErr_Occurred())
            PyErr_Print();

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
        Init(res);
        // Init will set the type to string - override it to identify as
        // and object.
        HeaderPtr()[0] = OBJECT;
        Py_DECREF(res);
    }

    if(this->size > 0 && HeaderPtr()[0] != EMPTY)
        alloced = true;
}


/*****************************************************************************
 * Function: Buffer::Reset
 *
 * Purpose:
 *   Cleans up buffer data.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Wed Jan  7 10:05:02 PST 2009
 *
 * Modifications:
 *
 * ***************************************************************************/
void
Buffer::Reset()
{
    if(buffer != NULL)
    {
        if(alloced)
        {
            char *ptr = (char*) buffer;
            delete [] ptr;
        }
        this->buffer = NULL;
        this->data   = NULL;
    }

    this->size = 0;
    this->alloced = false;
}


/*****************************************************************************
 * Function: Buffer::MPIType
 *
 * Purpose:
 *   Returns the mpi type of the buffer.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Wed Jan  7 10:05:02 PST 2009
 *
 * Modifications:
409 410
 *   Cyrus Harrison, Tue Oct 11 10:48:06 PDT 2011
 *   Use long instead of int.
411 412 413 414 415 416 417
 *
 * ***************************************************************************/
MPI_Datatype
Buffer::MPIType()
{
    int type_id = TypeId();
    if(type_id == INTEGER)
418
        return MPI_LONG;
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    else if(type_id == DOUBLE)
        return MPI_DOUBLE;
    else if(type_id  == STRING || type_id == OBJECT)
        return MPI_CHAR;
    return NULL;
}


/*****************************************************************************
 * Function: Buffer::ToPyObject
 *
 * Purpose:
 *   Constructs a python object from the buffer data.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Wed Jan  7 10:05:02 PST 2009
 *
 * Modifications:
437 438 439
 *   Cyrus Harrison, Fri Jul  9 10:31:03 PDT 2010
 *   Use faster PyObject_CallFunctionObjArgs() instead of
 *   PyObject_CallFunction().
440 441 442 443 444
 *
 * ***************************************************************************/
PyObject *
Buffer::ToPyObject()
{
445
    // These access functions take care of uninited case.
446 447 448 449 450 451 452
    int type_id   = TypeId();
    int data_size = DataSize();

    if(type_id == INTEGER)
    {
        int *ptr = (int*)data;
        if(data_size == 1)
453
            return PyLong_FromLong(ptr[0]);
454 455 456 457
        else // return a list containing the int vals
        {
            PyObject *res = PyList_New(data_size);
            for(int i=0; i < data_size; i++)
458
                PyList_SET_ITEM(res,i,PyLong_FromLong(ptr[i]));
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
            return res;
        }
    }
    else if(type_id == DOUBLE)
    {
        double *ptr = (double*)data;
        if(data_size == 1)
            return PyFloat_FromDouble(ptr[0]);
        else // return a list containing the double vals
        {
            PyObject *res = PyList_New(data_size);
            for(int i=0; i < data_size; i++)
                PyList_SET_ITEM(res,i,PyFloat_FromDouble(ptr[i]));
            return res;
        }
    }
    else if(type_id == STRING || type_id == OBJECT)
    {
        char *ptr = (char*)data;
        PyObject *py_str = PyString_FromStringAndSize(ptr,data_size-1);
        if(type_id == STRING)
            return py_str;
481 482 483 484
        PyObject *res=PyObject_CallFunctionObjArgs(pickleLoads,py_str,NULL);
        // This case should't occur, but print an error msg just in case.
        if(res == NULL || PyErr_Occurred())
            PyErr_Print();
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
        Py_DECREF(py_str);
        return res;
    }

    return NULL;
}

/*****************************************************************************
 * Function: PickleInit
 *
 * Purpose:
 *   Gets pointers to python's pickle functions
 *
 * Programmer: Cyrus Harrison
 * Creation:   Wed Mar  4 15:33:39 PST 2009
 *
 * Modifications:
 *
 * ***************************************************************************/

void
Buffer::PickleInit()
{
    if(PickleReady())
        return;

    pickleModule = PyImport_ImportModule("pickle");  // new ref
camp's avatar
camp committed
512 513 514 515 516 517
    if( pickleModule )
    {
        pickleDict   = PyModule_GetDict(pickleModule); // borrowed ref
        pickleDumps  = PyDict_GetItemString(pickleDict, "dumps"); // borrowed ref
        pickleLoads  = PyDict_GetItemString(pickleDict, "loads"); // borrowed ref
    }
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
}

/*****************************************************************************
 * Function: PickleReady
 *
 * Purpose:
 *   Returns true if pickle functions are setup.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Thu Mar  5 08:29:22 PST 2009
 *
 * Modifications:
 *
 * ***************************************************************************/

bool
Buffer::PickleReady()
{
    return pickleModule != NULL;
}


/*****************************************************************************
 * Function: PickleCleanup
 *
 * Purpose:
 *   Decrements the ref count of the pickle module ref and cleans up
 *   borrowed references. 
 *
 * Note: This was created to clean up static members if necessary, in most
 *       cases these member will persist.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Thu Mar  5 08:29:22 PST 2009
 *
 * Modifications:
 *
 * ***************************************************************************/

void
Buffer::PickleCleanup()
{
    if(!PickleReady())
        return;

    Py_DECREF(pickleModule); // was true ref
    pickleModule = NULL;
    pickleDict   = NULL; // was borrowed ref
    pickleDumps  = NULL; // was borrowed ref
    pickleLoads  = NULL; // was borrowed ref

}

/*****************************************************************************
 * Function: Buffer::TotalBufferSize
 *
 * Purpose:
 *   Calculates buffer size, including header, for given data type and 
 *   data length.
 *
 * Programmer: Cyrus Harrison
 * Creation:   Fri Feb 19 08:12:50 PST 2010
 *
 * Modifications:
582 583
 *   Cyrus Harrison, Tue Oct 11 10:48:06 PDT 2011
 *   Use long instead of int.
584 585 586 587 588 589 590 591 592 593 594
 *
 * ***************************************************************************/

int
Buffer::TotalBufferSize(int type_id, int data_size)
{
    int res = 0;
    int header_size = 2 * sizeof(int);

    if(type_id == INTEGER)
    {
595
        res = header_size +  sizeof(long) * data_size;
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
    }
    else if(type_id == DOUBLE)
    {
        res = header_size + sizeof(double) * data_size;
    }
    else if(type_id == STRING || type_id == OBJECT)
    {
        res = header_size + data_size;
    }

    return res;
}