-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbasedb.hpp
2113 lines (1827 loc) · 66 KB
/
basedb.hpp
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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2021-2023 Lawrence Livermore National Security, LLC and other
* AMSLib Project Developers
*
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/
#ifndef __AMS_BASE_DB__
#define __AMS_BASE_DB__
#include <cstdint>
#include <experimental/filesystem>
#include <fstream>
#include <iostream>
#include <iterator>
#include <mutex>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>
#include "AMS.h"
#include "debug.h"
#include "wf/debug.h"
#include "wf/resource_manager.hpp"
#include "wf/utils.hpp"
namespace fs = std::experimental::filesystem;
#ifdef __ENABLE_REDIS__
#include <sw/redis++/redis++.h>
#include <iomanip>
#warning Redis is currently not supported/tested
#endif
#ifdef __ENABLE_HDF5__
#include <H5Ipublic.h>
#include <hdf5.h>
#define HDF5_ERROR(Eid) \
if (Eid < 0) { \
std::cerr << "[Error] Happened in " << __FILE__ << ":" \
<< __PRETTY_FUNCTION__ << " ( " << __LINE__ << ")\n"; \
exit(-1); \
}
#endif
#ifdef __AMS_ENABLE_CALIPER__
#include <caliper/cali_macros.h>
#endif
#ifdef __ENABLE_RMQ__
#include <amqpcpp.h>
#include <amqpcpp/libevent.h>
#include <amqpcpp/linux_tcp.h>
#include <amqpcpp/throttle.h>
#include <event2/event-config.h>
#include <event2/event.h>
#include <event2/thread.h>
#include <openssl/err.h>
#include <openssl/opensslv.h>
#include <openssl/ssl.h>
#include <algorithm>
#include <chrono>
#include <deque>
#include <future>
#include <random>
#include <thread>
#include <tuple>
#endif // __ENABLE_RMQ__
namespace ams
{
namespace db
{
AMSDBType getDBType(std::string type);
std::string getDBTypeAsStr(AMSDBType type);
/**
* @brief A simple pure virtual interface to store data in some
* persistent storage device
*/
class BaseDB
{
/** @brief unique id of the process running this simulation */
uint64_t id;
/** @brief True if surrogate model update is allowed */
bool allowUpdate;
public:
BaseDB(const BaseDB&) = delete;
BaseDB& operator=(const BaseDB&) = delete;
BaseDB(uint64_t id) : id(id), allowUpdate(false) {}
BaseDB(uint64_t id, bool allowUpdate) : id(id), allowUpdate(allowUpdate) {}
virtual void close() {}
virtual ~BaseDB() {}
/**
* @brief Define the type of the DB (File, Redis etc)
*/
virtual std::string type() = 0;
virtual AMSDBType dbType() = 0;
/**
* @brief Takes an input and an output vector each holding 1-D vectors data, and
* store. them in persistent data storage.
* @param[in] num_elements Number of elements of each 1-D vector
* @param[in] inputs Vector of 1-D vectors containing the inputs to be stored
* @param[in] inputs Vector of 1-D vectors, each 1-D vectors contains
* 'num_elements' values to be stored
* @param[in] outputs Vector of 1-D vectors, each 1-D vectors contains
* 'num_elements' values to be stored
*/
virtual void store(size_t num_elements,
std::vector<double*>& inputs,
std::vector<double*>& outputs,
bool* predicate = nullptr) = 0;
virtual void store(size_t num_elements,
std::vector<float*>& inputs,
std::vector<float*>& outputs,
bool* predicate = nullptr) = 0;
uint64_t getId() const { return id; }
bool allowModelUpdate() { return allowUpdate; }
virtual bool updateModel() { return false; }
virtual std::string getLatestModel() { return {}; }
virtual bool storePredicate() const { return false; }
};
/**
* @brief A pure virtual interface for data bases storing data using
* some file format (filesystem DB).
*/
class FileDB : public BaseDB
{
protected:
/** @brief Path to file to write data to */
std::string fn;
/** @brief absolute path to directory storing the data */
std::string fp;
/**
* @brief check error code, if it exists print message and exit application
* @param[in] ec error code
*/
void checkError(std::error_code& ec)
{
if (ec) {
std::cerr << "Error in is_regular_file: " << ec.message();
exit(-1);
}
}
public:
/**
* @brief Takes an input and an output vector each holding 1-D vectors data, and
* store. them in persistent data storage.
* @param[in] path Path to an existing directory where to store our data
* @param[in] suffix The suffix of the file to write to
* @param[in] rId a unique Id for each process taking part in a distributed
* execution (rank-id)
* */
FileDB(std::string path,
std::string fn,
const std::string suffix,
uint64_t rId)
: BaseDB(rId)
{
fs::path Path(path);
std::error_code ec;
if (!fs::exists(Path, ec)) {
std::cerr << "[ERROR]: Path:'" << path << "' does not exist\n";
exit(-1);
}
checkError(ec);
if (!fs::is_directory(Path, ec)) {
std::cerr << "[ERROR]: Path:'" << path << "' is a file NOT a directory\n";
exit(-1);
}
Path = fs::absolute(Path);
fp = Path.string();
// We can now create the filename
std::string dbfn(fn + "_");
dbfn += std::to_string(rId) + suffix;
Path /= fs::path(dbfn);
this->fn = fs::absolute(Path).string();
DBG(DB, "File System DB writes to file %s", this->fn.c_str())
}
};
class csvDB final : public FileDB
{
private:
/** @brief file descriptor */
bool writeHeader;
std::fstream fd;
PERFFASPECT()
template <typename TypeValue>
void _store(size_t num_elements,
std::vector<TypeValue*>& inputs,
std::vector<TypeValue*>& outputs)
{
DBG(DB,
"DB of type %s stores %ld elements of input/output dimensions (%lu, "
"%lu)",
type().c_str(),
num_elements,
inputs.size(),
outputs.size())
CALIPER(CALI_MARK_BEGIN("STORE_CSV");)
const size_t num_in = inputs.size();
const size_t num_out = outputs.size();
if (writeHeader) {
for (size_t i = 0; i < num_in; i++)
fd << "input_" << i << ":";
for (size_t i = 0; i < num_out - 1; i++)
fd << "output_" << i << ":";
fd << "output_" << num_out - 1 << "\n";
writeHeader = false;
}
for (size_t i = 0; i < num_elements; i++) {
for (size_t j = 0; j < num_in; j++) {
fd << inputs[j][i] << ":";
}
for (size_t j = 0; j < num_out - 1; j++) {
fd << outputs[j][i] << ":";
}
fd << outputs[num_out - 1][i] << "\n";
}
CALIPER(CALI_MARK_END("STORE_CSV");)
}
public:
csvDB(const csvDB&) = delete;
csvDB& operator=(const csvDB&) = delete;
/**
* @brief constructs the class and opens the file to write to
* @param[in] fn Name of the file to store data to
* @param[in] rId a unique Id for each process taking part in a distributed
* execution (rank-id)
*/
csvDB(std::string path, std::string fn, uint64_t rId)
: FileDB(path, fn, ".csv", rId)
{
writeHeader = !fs::exists(this->fn);
fd.open(this->fn, std::ios_base::app | std::ios_base::out);
if (!fd.is_open()) {
std::cerr << "Cannot open db file: " << this->fn << std::endl;
}
DBG(DB, "DB Type: %s", type().c_str())
}
/**
* @brief deconstructs the class and closes the file
*/
~csvDB()
{
DBG(DB, "Closing File: %s %s", type().c_str(), this->fn.c_str())
fd.close();
}
virtual void store(size_t num_elements,
std::vector<float*>& inputs,
std::vector<float*>& outputs,
bool* predicate = nullptr) override
{
CFATAL(CSV,
predicate != nullptr,
"CSV database does not support storing uq-predicates")
_store(num_elements, inputs, outputs);
}
virtual void store(size_t num_elements,
std::vector<double*>& inputs,
std::vector<double*>& outputs,
bool* predicate = nullptr) override
{
CFATAL(CSV,
predicate != nullptr,
"CSV database does not support storing uq-predicates")
_store(num_elements, inputs, outputs);
}
/**
* @brief Define the type of the DB (File, Redis etc)
*/
std::string type() override { return "csv"; }
/**
* @brief Return the DB enumerationt type (File, Redis etc)
*/
AMSDBType dbType() override { return AMSDBType::AMS_CSV; };
/**
* @brief Takes an input and an output vector each holding 1-D vectors data, and
* store them into a csv file delimited by ':'. This should never be used for
* large scale simulations as txt/csv format will be extremely slow.
* @param[in] num_elements Number of elements of each 1-D vector
* @param[in] inputs Vector of 1-D vectors containing the inputs to bestored
* @param[in] inputs Vector of 1-D vectors, each 1-D vectors contains
* 'num_elements' values to be stored
* @param[in] outputs Vector of 1-D vectors, each 1-D vectors contains
* 'num_elements' values to be stored
*/
};
#ifdef __ENABLE_HDF5__
class hdf5DB final : public FileDB
{
private:
/** @brief file descriptor */
hid_t HFile;
/** @brief vector holding the hdf5 dataset descriptor.
* We currently store every input on a separate dataset
*/
std::vector<hid_t> HDIsets;
/** @brief vector holding the hdf5 dataset descriptor.
* We currently store every output on a separate dataset
*/
std::vector<hid_t> HDOsets;
/** @brief Total number of elements we have in our file */
hsize_t totalElements;
hid_t HDType;
/** @brief the dataset descriptor of the predicates */
hid_t pSet;
const bool predicateStore;
/** @brief create or get existing hdf5 dataset with the provided name
* storing data as Ckunked pieces. The Chunk value controls the chunking
* performed by HDF5 and thus controls the write performance
* @param[in] group in which we will store data under
* @param[in] dName name of the data set
* @param[in] dataType dataType to be stored for this dataset
* @param[in] Chunk chunk size of dataset used by HDF5.
* @reval dataset HDF5 key value
*/
hid_t getDataSet(hid_t group,
std::string dName,
hid_t dataType,
const size_t Chunk = 1024L);
/**
* @brief Create the HDF5 datasets and store their descriptors in the in/out
* vectors
* @param[in] num_elements of every vector
* @param[in] numIn number of input 1-D vectors
* @param[in] numOut number of output 1-D vectors
*/
void createDataSets(size_t numElements,
const size_t numIn,
const size_t numOut);
/**
* @brief Write all the data in the vectors in the respective datasets.
* @param[in] dsets Vector containing the hdf5-dataset descriptor for every
* vector to be written
* @param[in] data vectors containing 1-D vectors of numElements values each
* to be written in the db.
* @param[in] numElements The number of elements each vector has
*/
template <typename TypeValue>
void writeDataToDataset(std::vector<hid_t>& dsets,
std::vector<TypeValue*>& data,
size_t numElements);
/** @brief Writes a single 1-D vector to the dataset
* @param[in] dSet the dataset to write the data to
* @param[in] data the data we need to write
* @param[in] elements the number of data elements we have
* @param[in] datatype of elements we will write
*/
void writeVecToDataset(hid_t dSet, void* data, size_t elements, hid_t DType);
PERFFASPECT()
template <typename TypeValue>
void _store(size_t num_elements,
std::vector<TypeValue*>& inputs,
std::vector<TypeValue*>& outputs,
bool* predicate = nullptr);
public:
// Delete copy constructors. We do not want to copy the DB around
hdf5DB(const hdf5DB&) = delete;
hdf5DB& operator=(const hdf5DB&) = delete;
/**
* @brief constructs the class and opens the hdf5 file to write to
* @param[in] path path to directory to open/create the file
* @param[in] fn Name of the file to store the data to
* @param[in] rId a unique Id for each process taking part in a distributed
* execution (rank-id)
*/
hdf5DB(std::string path,
std::string domain_name,
std::string fn,
uint64_t rId,
bool predicate = false);
/**
* @brief deconstructs the class and closes the file
*/
~hdf5DB();
/**
* @brief Define the type of the DB
*/
std::string type() override { return "hdf5"; }
/**
* @brief Return the DB enumerationt type (File, Redis etc)
*/
AMSDBType dbType() override { return AMSDBType::AMS_HDF5; };
/**
* @brief Takes an input and an output vector each holding 1-D vectors data,
* and store them into a hdf5 file delimited by ':'. This should never be used
* for large scale simulations as txt/hdf5 format will be extremely slow.
* @param[in] num_elements Number of elements of each 1-D vector
* @param[in] inputs Vector of 1-D vectors containing the inputs to bestored
* @param[in] inputs Vector of 1-D vectors, each 1-D vectors contains
* 'num_elements' values to be stored
* @param[in] outputs Vector of 1-D vectors, each 1-D vectors contains
* 'num_elements' values to be stored
*/
void store(size_t num_elements,
std::vector<float*>& inputs,
std::vector<float*>& outputs,
bool* predicate = nullptr) override;
/**
* @brief Takes an input and an output vector each holding 1-D vectors data,
* and store them into a hdf5 file delimited by ':'. This should never be used
* for large scale simulations as txt/hdf5 format will be extremely slow.
* @param[in] num_elements Number of elements of each 1-D vector
* @param[in] inputs Vector of 1-D vectors containing the inputs to bestored
* @param[in] inputs Vector of 1-D vectors, each 1-D vectors contains
* 'num_elements' values to be stored
* @param[in] outputs Vector of 1-D vectors, each 1-D vectors contains
* 'num_elements' values to be stored
*/
void store(size_t num_elements,
std::vector<double*>& inputs,
std::vector<double*>& outputs,
bool* predicate = nullptr) override;
/**
* @brief Returns whether the DB can also store predicate information for debug
* purposes
*/
bool storePredicate() const override { return predicateStore; }
};
#endif
#ifdef __ENABLE_REDIS__
template <typename TypeValue>
class RedisDB : public BaseDB<TypeValue>
{
const std::string _fn; // path to the file storing the DB access config
uint64_t _dbid;
sw::redis::Redis* _redis;
uint64_t keyId;
public:
RedisDB(const RedisDB&) = delete;
RedisDB& operator=(const RedisDB&) = delete;
/**
* @brief constructs the class and opens the file to write to
* @param[in] fn Name of the file to store data to
* @param[in] rId a unique Id for each process taking part in a distributed
* execution (rank-id)
*/
RedisDB(std::string fn, uint64_t rId)
: BaseDB<TypeValue>(rId), _fn(fn), _redis(nullptr), keyId(0)
{
_dbid = reinterpret_cast<uint64_t>(this);
auto connection_info = read_json(fn);
sw::redis::ConnectionOptions connection_options;
connection_options.type = sw::redis::ConnectionType::TCP;
connection_options.host = connection_info["host"];
connection_options.port = std::stoi(connection_info["service-port"]);
connection_options.password = connection_info["database-password"];
connection_options.db = 0; // Optionnal, 0 is the default
connection_options.tls.enabled =
true; // Required to connect to PDS within LC
connection_options.tls.cacert = connection_info["cert"];
sw::redis::ConnectionPoolOptions pool_options;
pool_options.size = 100; // Pool size, i.e. max number of connections.
_redis = new sw::redis::Redis(connection_options, pool_options);
}
~RedisDB()
{
std::cerr << "Deleting RedisDB object\n";
delete _redis;
}
inline std::string type() override { return "RedisDB"; }
/**
* @brief Return the DB enumerationt type (File, Redis etc)
*/
AMSDBType dbType() { return AMSDBType::REDIS; };
inline std::string info() { return _redis->info(); }
// Return the number of keys in the DB
inline long long dbsize() { return _redis->dbsize(); }
/* !
* ! WARNING: Flush the entire Redis, accross all DBs!
* !
*/
inline void flushall() { _redis->flushall(); }
/*
* ! WARNING: Flush the entire current DB!
* !
*/
inline void flushdb() { _redis->flushdb(); }
std::unordered_map<std::string, std::string> read_json(std::string fn)
{
std::ifstream config;
std::unordered_map<std::string, std::string> connection_info = {
{"database-password", ""},
{"host", ""},
{"service-port", ""},
{"cert", ""},
};
config.open(fn, std::ifstream::in);
if (config.is_open()) {
std::string line;
// Quite inefficient parsing (to say the least..) but the file to parse is
// small (4 lines)
// TODO: maybe use Boost or another JSON library
while (std::getline(config, line)) {
if (line.find("{") != std::string::npos ||
line.find("}") != std::string::npos) {
continue;
}
line.erase(std::remove(line.begin(), line.end(), ' '), line.end());
line.erase(std::remove(line.begin(), line.end(), ','), line.end());
line.erase(std::remove(line.begin(), line.end(), '"'), line.end());
std::string key = line.substr(0, line.find(':'));
line.erase(0, line.find(":") + 1);
connection_info[key] = line;
// std::cerr << "key=" << key << " and value=" << line << std::endl;
}
config.close();
} else {
std::cerr << "Config located at: " << fn << std::endl;
throw std::runtime_error("Could not open Redis config file");
}
return connection_info;
}
void store(size_t num_elements,
std::vector<TypeValue*>& inputs,
std::vector<TypeValue*>& outputs,
bool predicate = nullptr) override
{
CFATAL(REDIS,
predicate != nullptr,
"REDIS database does not support storing uq-predicates")
const size_t num_in = inputs.size();
const size_t num_out = outputs.size();
// TODO:
// Make insertion more efficient.
// Right now it's pretty naive and expensive
auto start = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < num_elements; i++) {
std::string key = std::to_string(_dbid) + ":" + std::to_string(keyId) +
":" +
std::to_string(i); // In Redis a key must be a string
std::ostringstream fd;
for (size_t j = 0; j < num_in; j++) {
fd << inputs[j][i] << ":";
}
for (size_t j = 0; j < num_out - 1; j++) {
fd << outputs[j][i] << ":";
}
fd << outputs[num_out - 1][i];
std::string val(fd.str());
_redis->set(key, val);
}
keyId += 1;
auto stop = std::chrono::high_resolution_clock::now();
auto duration =
std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);
auto nb_keys = this->dbsize();
std::cout << std::setprecision(2) << "Inserted " << num_elements
<< " keys [Total keys = " << nb_keys << "] into RedisDB [Total "
<< duration.count() << "ms, "
<< static_cast<double>(num_elements) / duration.count()
<< " key/ms]" << std::endl;
}
};
#endif // __ENABLE_REDIS__
#ifdef __ENABLE_RMQ__
enum RMQConnectionStatus { FAILED, CONNECTED, CLOSED, ERROR };
/**
* @brief AMS represents the header as follows:
* The header is 16 bytes long:
* - 1 byte is the size of the header (here 16). Limit max: 255
* - 1 byte is the precision (4 for float, 8 for double). Limit max: 255
* - 2 bytes are the MPI rank (0 if AMS is not running with MPI). Limit max: 65535
* - 2 bytes to store the size of the MSG domain name. Limit max: 65535
* - 4 bytes are the number of elements in the message. Limit max: 2^32 - 1
* - 2 bytes are the input dimension. Limit max: 65535
* - 2 bytes are the output dimension. Limit max: 65535
* - 2 bytes for padding. Limit max: 2^16 - 1
*
* |_Header_|_Datatype_|___Rank___|__DomainSize__|__#elems__|___InDim____|___OutDim___|_Pad_|.real data.|
* ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
* | Byte 1 | Byte 2 | Byte 3-4 | Byte 5-6 |Byte 6-10 | Byte 10-12 | Byte 12-14 |-----| Byte 16-k |
*
* where X = datatype * num_element * (InDim + OutDim). Total message size is 16+k.
*
* The data starts at byte 16, ends at byte k.
* The data is structured as pairs of input/outputs. Let K be the total number of
* elements, then we have K pairs of inputs/outputs (either float or double):
*
* |__Header_(16B)__|__Input 1__|__Output 1__|...|__Input_K__|__Output_K__|
*/
struct AMSMsgHeader {
/** @brief Header size (bytes) */
uint8_t hsize;
/** @brief Data type size (bytes) */
uint8_t dtype;
/** @brief MPI rank */
uint16_t mpi_rank;
/** @brief Domain Name Size */
uint16_t domain_size;
/** @brief Number of elements */
uint32_t num_elem;
/** @brief Inputs dimension */
uint16_t in_dim;
/** @brief Outputs dimension */
uint16_t out_dim;
/**
* @brief Constructor for AMSMsgHeader
* @param[in] mpi_rank MPI rank
* @param[in] num_elem Number of elements (input/outputs)
* @param[in] in_dim Inputs dimension
* @param[in] out_dim Outputs dimension
*/
AMSMsgHeader(size_t mpi_rank,
size_t domain_size,
size_t num_elem,
size_t in_dim,
size_t out_dim,
size_t type_size);
/**
* @brief Constructor for AMSMsgHeader
* @param[in] mpi_rank MPI rank
* @param[in] num_elem Number of elements (input/outputs)
* @param[in] in_dim Inputs dimension
* @param[in] out_dim Outputs dimension
*/
AMSMsgHeader(uint16_t mpi_rank,
uint16_t domain_size,
uint32_t num_elem,
uint16_t in_dim,
uint16_t out_dim,
uint8_t type_size);
/**
* @brief Return the size of a header in the AMS protocol.
* @return The size of a message header in AMS (in byte)
*/
static size_t constexpr size()
{
return ((sizeof(hsize) + sizeof(dtype) + sizeof(mpi_rank) +
sizeof(domain_size) + sizeof(num_elem) + sizeof(in_dim) +
sizeof(out_dim) + sizeof(double) - 1) /
sizeof(double)) *
sizeof(double);
}
/**
* @brief Fill an empty buffer with a valid header.
* @param[in] data_blob The buffer to fill
* @return The number of bytes in the header or 0 if error
*/
size_t encode(uint8_t* data_blob);
/**
* @brief Return a valid header based on a pre-existing data buffer
* @param[in] data_blob The buffer to fill
* @return An AMSMsgHeader with the correct attributes
*/
static AMSMsgHeader decode(uint8_t* data_blob);
};
/**
* @brief Class representing a message for the AMSLib
*/
class AMSMessage
{
public:
/** @brief message ID */
int _id;
/** @brief The MPI rank (0 if MPI is not used) */
uint64_t _rank;
/** @brief The data represented as a binary blob */
uint8_t* _data;
/** @brief The total size of the binary blob in bytes */
size_t _total_size;
/** @brief The number of input/output pairs */
size_t _num_elements;
/** @brief The dimensions of inputs */
size_t _input_dim;
/** @brief The dimensions of outputs */
size_t _output_dim;
/**
* @brief Empty constructor
*/
AMSMessage()
: _id(0),
_rank(0),
_num_elements(0),
_input_dim(0),
_output_dim(0),
_data(nullptr),
_total_size(0)
{
}
/**
* @brief Constructor
* @param[in] id ID of the message
* @param[in] rId MPI Rank of the messages (0 default)
* @param[in] num_elements Number of elements
* @param[in] inputs Inputs
* @param[in] outputs Outputs
*/
template <typename TypeValue>
AMSMessage(int id,
uint64_t rId,
std::string& domain_name,
size_t num_elements,
const std::vector<TypeValue*>& inputs,
const std::vector<TypeValue*>& outputs)
: _id(id),
_rank(rId),
_num_elements(num_elements),
_input_dim(inputs.size()),
_output_dim(outputs.size()),
_data(nullptr),
_total_size(0)
{
AMSMsgHeader header(_rank,
domain_name.size(),
_num_elements,
_input_dim,
_output_dim,
sizeof(TypeValue));
_total_size = AMSMsgHeader::size() + domain_name.size() +
getTotalElements() * sizeof(TypeValue);
auto& rm = ams::ResourceManager::getInstance();
_data = rm.allocate<uint8_t>(_total_size, AMSResourceType::AMS_HOST);
size_t current_offset = header.encode(_data);
std::memcpy(&_data[current_offset],
domain_name.c_str(),
domain_name.size());
current_offset += domain_name.size();
current_offset +=
encode_data(reinterpret_cast<TypeValue*>(_data + current_offset),
inputs,
outputs);
DBG(AMSMessage, "Allocated message %d: %p", _id, _data);
}
/**
* @brief Constructor
* @param[in] id ID of the message
* @param[in] rId MPI rank of the message
* @param[in] data Pointer containing data
*/
AMSMessage(int id, uint64_t rId, uint8_t* data);
AMSMessage(const AMSMessage& other)
{
DBG(AMSMessage, "Copy AMSMessage : %p -- %d", other._data, other._id);
swap(other);
};
/**
* @brief Internal Method swapping for AMSMessage
* @param[in] other Message to swap
*/
void swap(const AMSMessage& other);
AMSMessage& operator=(const AMSMessage&) = delete;
AMSMessage(AMSMessage&& other) noexcept { *this = std::move(other); }
AMSMessage& operator=(AMSMessage&& other) noexcept
{
// DBG(AMSMessage, "Move AMSMessage : %p -- %d", other._data, other._id);
if (this != &other) {
swap(other);
other._data = nullptr;
}
return *this;
}
/**
* @brief Fill a buffer with a data section starting at a given position.
* @param[in] data_blob The buffer to fill
* @param[in] offset Position where to start writing in the buffer
* @param[in] inputs Inputs
* @param[in] outputs Outputs
* @return The number of bytes in the message or 0 if error
*/
template <typename TypeValue>
size_t encode_data(TypeValue* data_blob,
const std::vector<TypeValue*>& inputs,
const std::vector<TypeValue*>& outputs)
{
size_t x_dim = _input_dim + _output_dim;
if (!data_blob) return 0;
// Creating the body part of the messages
for (size_t i = 0; i < _num_elements; i++) {
for (size_t j = 0; j < _input_dim; j++) {
data_blob[i * x_dim + j] = inputs[j][i];
}
}
for (size_t i = 0; i < _num_elements; i++) {
for (size_t j = 0; j < _output_dim; j++) {
data_blob[i * x_dim + _input_dim + j] = outputs[j][i];
}
}
return (x_dim * _num_elements) * sizeof(TypeValue);
}
/**
* @brief Return the total number of elements in this message
* @return Size in bytes of the data portion
*/
size_t getTotalElements() const
{
return (_num_elements * (_input_dim + _output_dim));
}
/**
* @brief Return the underlying data pointer
* @return Data pointer (binary blob)
*/
uint8_t* data() const { return _data; }
/**
* @brief Return message ID
* @return message ID
*/
int id() const { return _id; }
/**
* @brief Return MPI rank
* @return MPI rank
*/
int rank() const { return _rank; }
/**
* @brief Return the size in bytes of the underlying binary blob
* @return Byte size of data pointer
*/
size_t size() const { return _total_size; }
~AMSMessage()
{
DBG(AMSMessage,
"Destroying message %d: %p (underlying memory NOT freed)",
_id,
_data)
}
}; // class AMSMessage
/**
* @brief Structure that represents incoming RabbitMQ messages.
*/
class AMSMessageInbound
{
public:
/** @brief Delivery tag (ID of the message) */
uint64_t id;
/** @brief MPI rank */
uint64_t rId;
/** @brief message content (body) */
std::string body;
/** @brief RabbitMQ exchange from which the message has been received */
std::string exchange;
/** @brief routing key */
std::string routing_key;
/** @brief True if messages has been redelivered */
bool redelivered;
AMSMessageInbound() = default;
AMSMessageInbound(AMSMessageInbound&) = default;
AMSMessageInbound& operator=(AMSMessageInbound&) = default;
AMSMessageInbound(AMSMessageInbound&&) = default;
AMSMessageInbound& operator=(AMSMessageInbound&&) = default;
AMSMessageInbound(uint64_t id,
uint64_t rId,
std::string body,
std::string exchange,
std::string routing_key,
bool redelivered);
/**
* @brief Check if a message is empty.
* @return True if message is empty
*/
bool empty();
/**
* @brief Check if a message is empty.
* @return True if message is empty.
*/
bool isTraining();
/**
* @brief Get the model path from the message.
* @return Return model path or empty string if no model available.
*/
std::string getModelPath();
private: