1 2 3 4 5 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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 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 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 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 351 352 353 354 355 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 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 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 512 513 514 515 516 517 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 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
|
/**
* Orthanc - A Lightweight, RESTful DICOM Store
* Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
* Department, University Hospital of Liege, Belgium
* Copyright (C) 2017-2023 Osimis S.A., Belgium
* Copyright (C) 2021-2023 Sebastien Jodogne, ICTEAM UCLouvain, Belgium
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
#include "StorageBackend.h"
#if HAS_ORTHANC_EXCEPTION != 1
# error HAS_ORTHANC_EXCEPTION must be set to 1
#endif
#include "../../Framework/Common/BinaryStringValue.h"
#include "../../Framework/Common/ResultFileValue.h"
#include <Compatibility.h> // For std::unique_ptr<>
#include <Logging.h>
#include <OrthancException.h>
#include <boost/thread.hpp>
#include <cassert>
#include <limits>
#define ORTHANC_PLUGINS_DATABASE_CATCH \
catch (::Orthanc::OrthancException& e) \
{ \
return static_cast<OrthancPluginErrorCode>(e.GetErrorCode()); \
} \
catch (::std::runtime_error& e) \
{ \
std::string s = "Exception in storage area back-end: " + std::string(e.what()); \
OrthancPluginLogError(context_, s.c_str()); \
return OrthancPluginErrorCode_DatabasePlugin; \
} \
catch (...) \
{ \
OrthancPluginLogError(context_, "Native exception"); \
return OrthancPluginErrorCode_DatabasePlugin; \
}
namespace OrthancDatabases
{
class StorageBackend::ReadWholeOperation : public StorageBackend::IDatabaseOperation
{
private:
IFileContentVisitor& visitor_;
const char* uuid_;
OrthancPluginContentType type_;
public:
ReadWholeOperation(IFileContentVisitor& visitor,
const char* uuid,
OrthancPluginContentType type) :
visitor_(visitor),
uuid_(uuid),
type_(type)
{
}
virtual void Execute(StorageBackend::IAccessor& accessor) ORTHANC_OVERRIDE
{
accessor.ReadWhole(visitor_, uuid_, type_);
}
};
StorageBackend::StorageBackend(IDatabaseFactory* factory,
unsigned int maxRetries) :
manager_(factory),
maxRetries_(maxRetries)
{
}
void StorageBackend::AccessorBase::Create(const std::string& uuid,
const void* content,
size_t size,
OrthancPluginContentType type)
{
DatabaseManager::Transaction transaction(manager_, TransactionType_ReadWrite);
{
DatabaseManager::CachedStatement statement(
STATEMENT_FROM_HERE, manager_,
"INSERT INTO StorageArea VALUES (${uuid}, ${content}, ${type})");
statement.SetParameterType("uuid", ValueType_Utf8String);
statement.SetParameterType("content", ValueType_InputFile);
statement.SetParameterType("type", ValueType_Integer64);
Dictionary args;
args.SetUtf8Value("uuid", uuid);
args.SetFileValue("content", content, size);
args.SetIntegerValue("type", type);
statement.Execute(args);
}
transaction.Commit();
}
void StorageBackend::AccessorBase::ReadWhole(StorageBackend::IFileContentVisitor& visitor,
const std::string& uuid,
OrthancPluginContentType type)
{
DatabaseManager::Transaction transaction(manager_, TransactionType_ReadOnly);
{
DatabaseManager::CachedStatement statement(
STATEMENT_FROM_HERE, manager_,
"SELECT content FROM StorageArea WHERE uuid=${uuid} AND type=${type}");
statement.SetParameterType("uuid", ValueType_Utf8String);
statement.SetParameterType("type", ValueType_Integer64);
Dictionary args;
args.SetUtf8Value("uuid", uuid);
args.SetIntegerValue("type", type);
statement.Execute(args);
if (statement.IsDone())
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_UnknownResource);
}
else if (statement.GetResultFieldsCount() != 1)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_Database);
}
else
{
const IValue& value = statement.GetResultField(0);
switch (value.GetType())
{
case ValueType_ResultFile:
{
std::string content;
dynamic_cast<const ResultFileValue&>(value).ReadWhole(content);
visitor.Assign(content);
break;
}
case ValueType_BinaryString:
visitor.Assign(dynamic_cast<const BinaryStringValue&>(value).GetContent());
break;
default:
throw Orthanc::OrthancException(Orthanc::ErrorCode_Database);
}
}
}
transaction.Commit();
if (!visitor.IsSuccess())
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_Database, "Could not read attachment from the storage area");
}
}
void StorageBackend::AccessorBase::ReadRange(IFileContentVisitor& visitor,
const std::string& uuid,
OrthancPluginContentType type,
uint64_t start,
size_t length)
{
/**
* This is a generic implementation, that will only work if
* "ResultFileValue" is implemented by the database backend. For
* instance, this will *not* work with MySQL, as the latter uses
* BLOB columns to store files.
**/
DatabaseManager::Transaction transaction(manager_, TransactionType_ReadOnly);
{
DatabaseManager::CachedStatement statement(
STATEMENT_FROM_HERE, manager_,
"SELECT content FROM StorageArea WHERE uuid=${uuid} AND type=${type}");
statement.SetParameterType("uuid", ValueType_Utf8String);
statement.SetParameterType("type", ValueType_Integer64);
Dictionary args;
args.SetUtf8Value("uuid", uuid);
args.SetIntegerValue("type", type);
statement.Execute(args);
if (statement.IsDone())
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_UnknownResource);
}
else if (statement.GetResultFieldsCount() != 1)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_Database);
}
else
{
const IValue& value = statement.GetResultField(0);
if (value.GetType() == ValueType_ResultFile)
{
std::string content;
dynamic_cast<const ResultFileValue&>(value).ReadRange(content, start, length);
visitor.Assign(content);
}
else
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_Database);
}
}
}
transaction.Commit();
if (!visitor.IsSuccess())
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_Database, "Could not read attachment from the storage area");
}
}
void StorageBackend::AccessorBase::Remove(const std::string& uuid,
OrthancPluginContentType type)
{
DatabaseManager::Transaction transaction(manager_, TransactionType_ReadWrite);
{
DatabaseManager::CachedStatement statement(
STATEMENT_FROM_HERE, manager_,
"DELETE FROM StorageArea WHERE uuid=${uuid} AND type=${type}");
statement.SetParameterType("uuid", ValueType_Utf8String);
statement.SetParameterType("type", ValueType_Integer64);
Dictionary args;
args.SetUtf8Value("uuid", uuid);
args.SetIntegerValue("type", type);
statement.Execute(args);
}
transaction.Commit();
}
static OrthancPluginContext* context_ = NULL;
static std::unique_ptr<StorageBackend> backend_;
static OrthancPluginErrorCode StorageCreate(const char* uuid,
const void* content,
int64_t size,
OrthancPluginContentType type)
{
class Operation : public StorageBackend::IDatabaseOperation
{
private:
const char* uuid_;
const void* content_;
int64_t size_;
OrthancPluginContentType type_;
public:
Operation(const char* uuid,
const void* content,
int64_t size,
OrthancPluginContentType type) :
uuid_(uuid),
content_(content),
size_(size),
type_(type)
{
}
virtual void Execute(StorageBackend::IAccessor& accessor) ORTHANC_OVERRIDE
{
accessor.Create(uuid_, content_, size_, type_);
}
};
try
{
if (backend_.get() == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
}
else
{
Operation operation(uuid, content, size, type);
backend_->Execute(operation);
return OrthancPluginErrorCode_Success;
}
}
ORTHANC_PLUGINS_DATABASE_CATCH;
}
#if defined(ORTHANC_PLUGINS_VERSION_IS_ABOVE)
# if ORTHANC_PLUGINS_VERSION_IS_ABOVE(1, 9, 0)
static OrthancPluginErrorCode StorageReadWhole(OrthancPluginMemoryBuffer64* target,
const char* uuid,
OrthancPluginContentType type)
{
class Visitor : public StorageBackend::IFileContentVisitor
{
private:
OrthancPluginMemoryBuffer64* target_;
bool success_;
public:
Visitor(OrthancPluginMemoryBuffer64* target) :
target_(target),
success_(false)
{
if (target == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_NullPointer);
}
}
virtual bool IsSuccess() const ORTHANC_OVERRIDE
{
return success_;
}
virtual void Assign(const std::string& content) ORTHANC_OVERRIDE
{
if (success_)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
else
{
assert(context_ != NULL);
if (OrthancPluginCreateMemoryBuffer64(context_, target_, static_cast<uint64_t>(content.size())) !=
OrthancPluginErrorCode_Success)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_NotEnoughMemory);
}
if (!content.empty())
{
memcpy(target_->data, content.c_str(), content.size());
}
success_ = true;
}
}
};
try
{
if (backend_.get() == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
}
else
{
Visitor visitor(target);
{
StorageBackend::ReadWholeOperation operation(visitor, uuid, type);
backend_->Execute(operation);
}
return OrthancPluginErrorCode_Success;
}
}
ORTHANC_PLUGINS_DATABASE_CATCH;
}
static OrthancPluginErrorCode StorageReadRange(OrthancPluginMemoryBuffer64* target,
const char* uuid,
OrthancPluginContentType type,
uint64_t start)
{
class Visitor : public StorageBackend::IFileContentVisitor
{
private:
OrthancPluginMemoryBuffer64* target_; // This buffer is already allocated by the Orthanc core
bool success_;
public:
Visitor(OrthancPluginMemoryBuffer64* target) :
target_(target),
success_(false)
{
if (target == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_NullPointer);
}
}
virtual bool IsSuccess() const ORTHANC_OVERRIDE
{
return success_;
}
virtual void Assign(const std::string& content) ORTHANC_OVERRIDE
{
if (success_)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
else
{
if (content.size() != target_->size)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
if (!content.empty())
{
memcpy(target_->data, content.c_str(), content.size());
}
success_ = true;
}
}
};
class Operation : public StorageBackend::IDatabaseOperation
{
private:
Visitor& visitor_;
const char* uuid_;
OrthancPluginContentType type_;
uint64_t start_;
size_t length_;
public:
Operation(Visitor& visitor,
const char* uuid,
OrthancPluginContentType type,
uint64_t start,
size_t length) :
visitor_(visitor),
uuid_(uuid),
type_(type),
start_(start),
length_(length)
{
}
virtual void Execute(StorageBackend::IAccessor& accessor) ORTHANC_OVERRIDE
{
accessor.ReadRange(visitor_, uuid_, type_, start_, length_);
}
};
try
{
if (backend_.get() == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
}
else
{
Visitor visitor(target);
{
Operation operation(visitor, uuid, type, start, target->size);
backend_->Execute(operation);
}
return OrthancPluginErrorCode_Success;
}
}
ORTHANC_PLUGINS_DATABASE_CATCH;
}
# endif
#endif
static OrthancPluginErrorCode StorageRead(void** data,
int64_t* size,
const char* uuid,
OrthancPluginContentType type)
{
class Visitor : public StorageBackend::IFileContentVisitor
{
private:
void** data_;
int64_t* size_;
bool success_;
public:
Visitor(void** data,
int64_t* size) :
data_(data),
size_(size),
success_(false)
{
}
~Visitor()
{
if (data_ != NULL /* this condition is invalidated by "Release()" */ &&
*data_ != NULL)
{
free(*data_);
}
}
void Release()
{
data_ = NULL;
}
virtual bool IsSuccess() const ORTHANC_OVERRIDE
{
return success_;
}
virtual void Assign(const std::string& content) ORTHANC_OVERRIDE
{
if (success_)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
else if (data_ == NULL)
{
// "Release()" has been called
throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
}
else
{
if (content.empty())
{
*data_ = NULL;
*size_ = 0;
}
else
{
*size_ = static_cast<int64_t>(content.size());
if (static_cast<size_t>(*size_) != content.size())
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_NotEnoughMemory,
"File cannot be stored in a 63bit buffer");
}
*data_ = malloc(*size_);
if (*data_ == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_NotEnoughMemory);
}
memcpy(*data_, content.c_str(), *size_);
}
success_ = true;
}
}
};
try
{
if (backend_.get() == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
}
else if (data == NULL ||
size == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_NullPointer);
}
else
{
Visitor visitor(data, size);
{
StorageBackend::ReadWholeOperation operation(visitor, uuid, type);
backend_->Execute(operation);
}
visitor.Release();
return OrthancPluginErrorCode_Success;
}
}
ORTHANC_PLUGINS_DATABASE_CATCH;
}
static OrthancPluginErrorCode StorageRemove(const char* uuid,
OrthancPluginContentType type)
{
class Operation : public StorageBackend::IDatabaseOperation
{
private:
const char* uuid_;
OrthancPluginContentType type_;
public:
Operation(const char* uuid,
OrthancPluginContentType type) :
uuid_(uuid),
type_(type)
{
}
virtual void Execute(StorageBackend::IAccessor& accessor) ORTHANC_OVERRIDE
{
accessor.Remove(uuid_, type_);
}
};
try
{
if (backend_.get() == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
}
else
{
Operation operation(uuid, type);
backend_->Execute(operation);
return OrthancPluginErrorCode_Success;
}
}
ORTHANC_PLUGINS_DATABASE_CATCH;
}
void StorageBackend::Register(OrthancPluginContext* context,
StorageBackend* backend)
{
if (context == NULL ||
backend == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_NullPointer);
}
else if (context_ != NULL ||
backend_.get() != NULL)
{
// This function can only be invoked once in the plugin
throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
}
else
{
context_ = context;
backend_.reset(backend);
bool hasLoadedV2 = false;
#if defined(ORTHANC_PLUGINS_VERSION_IS_ABOVE) // Macro introduced in Orthanc 1.3.1
# if ORTHANC_PLUGINS_VERSION_IS_ABOVE(1, 9, 0)
if (OrthancPluginCheckVersionAdvanced(context, 1, 9, 0) == 1)
{
OrthancPluginStorageReadRange readRange = NULL;
if (backend_->HasReadRange())
{
readRange = StorageReadRange;
}
OrthancPluginRegisterStorageArea2(context_, StorageCreate, StorageReadWhole, readRange, StorageRemove);
hasLoadedV2 = true;
}
# endif
#endif
if (!hasLoadedV2)
{
LOG(WARNING) << "Performance warning: Your version of the Orthanc core or SDK doesn't support reading of file ranges";
OrthancPluginRegisterStorageArea(context_, StorageCreate, StorageRead, StorageRemove);
}
LOG(WARNING) << "The storage area plugin will retry up to " << backend_->GetMaxRetries()
<< " time(s) in the case of a collision";
}
}
void StorageBackend::Finalize()
{
backend_.reset(NULL);
context_ = NULL;
}
class StorageBackend::StringVisitor : public StorageBackend::IFileContentVisitor
{
private:
std::string& target_;
bool success_;
public:
explicit StringVisitor(std::string& target) :
target_(target),
success_(false)
{
}
virtual bool IsSuccess() const ORTHANC_OVERRIDE
{
return success_;
}
virtual void Assign(const std::string& content) ORTHANC_OVERRIDE
{
if (success_)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
else
{
target_.assign(content);
success_ = true;
}
}
};
void StorageBackend::ReadWholeToString(std::string& target,
IAccessor& accessor,
const std::string& uuid,
OrthancPluginContentType type)
{
StringVisitor visitor(target);
accessor.ReadWhole(visitor, uuid, type);
if (!visitor.IsSuccess())
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
}
void StorageBackend::ReadRangeToString(std::string& target,
IAccessor& accessor,
const std::string& uuid,
OrthancPluginContentType type,
uint64_t start,
size_t length)
{
StringVisitor visitor(target);
accessor.ReadRange(visitor, uuid, type, start, length);
if (!visitor.IsSuccess())
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
}
void StorageBackend::Execute(IDatabaseOperation& operation)
{
std::unique_ptr<IAccessor> accessor(CreateAccessor());
if (accessor.get() == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
#if ORTHANC_FRAMEWORK_VERSION_IS_ABOVE(1, 9, 2)
unsigned int attempt = 0;
#endif
for (;;)
{
try
{
operation.Execute(*accessor);
return; // Success
}
catch (Orthanc::OrthancException& e)
{
#if ORTHANC_FRAMEWORK_VERSION_IS_ABOVE(1, 9, 2)
if (e.GetErrorCode() == Orthanc::ErrorCode_DatabaseCannotSerialize)
{
if (attempt >= maxRetries_)
{
throw;
}
else
{
attempt++;
// The "rand()" adds some jitter to de-synchronize writers
boost::this_thread::sleep(boost::posix_time::milliseconds(100 * attempt + 5 * (rand() % 10)));
}
}
else
{
throw;
}
#else
throw;
#endif
}
}
}
}
|