forked from heavyai/heavydb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathomnisql.cpp
1556 lines (1431 loc) · 54.2 KB
/
omnisql.cpp
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 2019 OmniSci, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file omnisql.cpp
* @author Wei Hong <[email protected]>
* @brief OmniSci SQL Client Tool
*
**/
#include <rapidjson/document.h>
#ifndef _WIN32
#include <termios.h>
#else
#include <Shlobj.h>
#include <windows.h>
#include "Shared/cleanup_global_namespace.h"
#endif
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <cmath>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <limits>
#include <numeric>
#include <sstream>
#include <string>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/protocol/TJSONProtocol.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/transport/TSocket.h>
#include "../Fragmenter/InsertOrderFragmenter.h"
#include "Logger/Logger.h"
#include "MapDRelease.h"
#include "Shared/StringTransform.h"
#include "Shared/ThriftClient.h"
#include "Shared/ThriftTypesConvert.h"
#include "Shared/base64.h"
#include "Shared/checked_alloc.h"
#include "Shared/misc.h"
#include "gen-cpp/OmniSci.h"
#include "include/linenoise.h"
#include "ClientContext.h"
#include "CommandFunctors.h"
#include "CommandHistoryFile.h"
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace std::string_literals;
const std::string OmniSQLRelease(MAPD_RELEASE);
namespace {
ClientContext* g_client_context_ptr{nullptr};
// global session is used to classify a session to deal with user's request on
// query execution and other services that thrift creates a new session ID
// i.e., global_session is a parent session of {service_session_1, ..., service_session_N}
static std::string global_session{""};
void completion(const char* buf, linenoiseCompletions* lc) {
CHECK(g_client_context_ptr);
thrift_with_retry(kGET_COMPLETION_HINTS, *g_client_context_ptr, buf);
for (const auto& completion_hint : g_client_context_ptr->completion_hints) {
for (const auto& hint_str : completion_hint.hints) {
CHECK_LE(completion_hint.replaced.size(), strlen(buf));
std::string partial_query(buf, buf + strlen(buf) - completion_hint.replaced.size());
partial_query += hint_str;
linenoiseAddCompletion(lc, partial_query.c_str());
}
}
}
#define LOAD_PATCH_SIZE 10000
void copy_table(char const* filepath, char const* table, ClientContext& context) {
if (context.session == INVALID_SESSION_ID) {
std::cerr << "Not connected to any databases." << std::endl;
return;
}
if (!boost::filesystem::exists(filepath)) {
std::cerr << "File does not exist." << std::endl;
return;
}
if (!thrift_with_retry(kGET_TABLE_DETAILS, context, table)) {
return;
}
const TRowDescriptor& row_desc = context.table_details.row_desc;
std::ifstream infile(filepath);
std::string line;
const char* delim = ",";
int l = strlen(filepath);
if (l >= 4 && strcmp(filepath + l - 4, ".tsv") == 0) {
delim = "\t";
}
std::vector<TStringRow> input_rows;
TStringRow row;
boost::char_separator<char> sep{delim, "", boost::keep_empty_tokens};
try {
while (std::getline(infile, line)) {
row.cols.clear();
boost::tokenizer<boost::char_separator<char>> tok{line, sep};
for (const auto& s : tok) {
TStringValue ts;
ts.str_val = s;
ts.is_null = s.empty();
row.cols.push_back(ts);
}
/*
std::cout << "Row: ";
for (const auto &p : row.cols) {
std::cout << p.str_val << ", ";
}
std::cout << std::endl;
*/
if (row.cols.size() != row_desc.size()) {
std::cerr << "Incorrect number of columns: (" << row.cols.size() << " vs "
<< row_desc.size() << ") " << line << std::endl;
continue;
}
input_rows.push_back(row);
if (input_rows.size() >= LOAD_PATCH_SIZE) {
try {
context.client.load_table(context.session, table, input_rows, {});
} catch (TOmniSciException& e) {
std::cerr << e.error_msg << std::endl;
}
input_rows.clear();
}
}
if (input_rows.size() > 0) {
context.client.load_table(context.session, table, input_rows, {});
}
} catch (TOmniSciException& e) {
std::cerr << e.error_msg << std::endl;
} catch (TException& te) {
std::cerr << "Thrift error: " << te.what() << std::endl;
}
}
void detect_table(char* file_name, TCopyParams& copy_params, ClientContext& context) {
if (context.session == INVALID_SESSION_ID) {
std::cerr << "Not connected to any databases." << std::endl;
return;
}
TDetectResult _return;
try {
context.client.detect_column_types(_return, context.session, file_name, copy_params);
// print result only for verifying detect_column_types api
// as this cmd seems never planned for public use
for (const auto& tct : _return.row_set.row_desc) {
printf("%20.20s ", tct.col_name.c_str());
}
printf("\n");
for (const auto& tct : _return.row_set.row_desc) {
printf("%20.20s ", type_info_from_thrift(tct.col_type).get_type_name().c_str());
}
printf("\n");
for (const auto& row : _return.row_set.rows) {
for (const auto& col : row.cols) {
printf("%20.20s ", col.val.str_val.c_str());
}
printf("\n");
}
// output CREATE TABLE command
std::stringstream oss;
oss << "CREATE TABLE your_table_name(";
for (size_t i = 0; i < _return.row_set.row_desc.size(); ++i) {
const auto tct = _return.row_set.row_desc[i];
oss << (i ? ", " : "") << tct.col_name << " "
<< type_info_from_thrift(tct.col_type).get_type_name();
if (type_info_from_thrift(tct.col_type).is_string()) {
oss << " ENCODING DICT";
}
if (type_info_from_thrift(tct.col_type).is_array()) {
oss << "[";
if (type_info_from_thrift(tct.col_type).get_size() > 0) {
oss << type_info_from_thrift(tct.col_type).get_size();
}
oss << "]";
}
}
oss << ");";
printf("\n%s\n", oss.str().c_str());
} catch (TOmniSciException& e) {
std::cerr << e.error_msg << std::endl;
} catch (TException& te) {
std::cerr << "Thrift error in detect_table: " << te.what() << std::endl;
}
}
size_t get_row_count(const TQueryResult& query_result) {
CHECK(!query_result.row_set.row_desc.empty());
if (query_result.row_set.columns.empty()) {
return 0;
}
CHECK_EQ(query_result.row_set.columns.size(), query_result.row_set.row_desc.size());
return query_result.row_set.columns.front().nulls.size();
}
void get_table_epoch(ClientContext& context, const std::string& table_specifier) {
if (table_specifier.size() == 0) {
std::cerr
<< "get table epoch requires table to be specified by name or by db_id:table_id"
<< std::endl;
return;
}
if (isdigit(table_specifier.at(0))) {
std::vector<std::string> split_result;
boost::split(
split_result,
table_specifier,
boost::is_any_of(":"),
boost::token_compress_on); // SplitVec == { "hello abc","ABC","aBc goodbye" }
if (split_result.size() != 2) {
std::cerr << "get table epoch does not contain db_id:table_id " << table_specifier
<< std::endl;
return;
}
// validate db identifier is a number
try {
context.db_id = std::stoi(split_result[0]);
} catch (std::exception& e) {
std::cerr << "non numeric db number: " << table_specifier << std::endl;
return;
}
// validate table identifier is a number
try {
context.table_id = std::stoi(split_result[1]);
} catch (std::exception& e) {
std::cerr << "non-numeric table number: " << table_specifier << std::endl;
return;
}
if (thrift_with_retry(kGET_TABLE_EPOCH, context, nullptr)) {
std::cout << "table epoch is " << context.epoch_value << std::endl;
}
} else {
// presume we have a table name
// get the db_id and table_id from the table metadata
if (thrift_with_retry(kGET_PHYSICAL_TABLES, context, nullptr)) {
if (std::find(context.names_return.begin(),
context.names_return.end(),
table_specifier) == context.names_return.end()) {
std::cerr << "table " << table_specifier << " not found" << std::endl;
return;
}
} else {
return;
}
context.table_name = table_specifier;
if (thrift_with_retry(kGET_TABLE_EPOCH_BY_NAME, context, nullptr)) {
std::cout << "table epoch is " << context.epoch_value << std::endl;
}
}
}
void set_table_epoch(ClientContext& context, const std::string& table_details) {
if (table_details.size() == 0) {
std::cerr << "set table epoch requires table and epoch to be specified by name epoch "
"or by db_id:table_id:epoch"
<< std::endl;
return;
}
if (isdigit(table_details.at(0))) {
std::vector<std::string> split_result;
boost::split(
split_result,
table_details,
boost::is_any_of(":"),
boost::token_compress_on); // SplitVec == { "hello abc","ABC","aBc goodbye" }
if (split_result.size() != 3) {
std::cerr << "Set table epoch does not contain db_id:table_id:epoch "
<< table_details << std::endl;
return;
}
// validate db identifier is a number
try {
context.db_id = std::stoi(split_result[0]);
} catch (std::exception& e) {
std::cerr << "non numeric db number: " << table_details << std::endl;
return;
}
// validate table identifier is a number
try {
context.table_id = std::stoi(split_result[1]);
} catch (std::exception& e) {
std::cerr << "non-numeric table number: " << table_details << std::endl;
return;
}
// validate epoch value
try {
context.epoch_value = std::stoi(split_result[2]);
} catch (std::exception& e) {
std::cerr << "non-numeric epoch number: " << table_details << std::endl;
return;
}
if (context.epoch_value < 0) {
std::cerr << "Epoch value can not be negative: " << table_details << std::endl;
return;
}
if (thrift_with_retry(kSET_TABLE_EPOCH, context, nullptr)) {
std::cout << "table epoch set" << std::endl;
}
} else {
std::vector<std::string> split_result;
boost::split(
split_result, table_details, boost::is_any_of(" "), boost::token_compress_on);
if (split_result.size() < 2) {
std::cerr << "Set table epoch does not contain table_name epoch " << std::endl;
return;
}
if (thrift_with_retry(kGET_PHYSICAL_TABLES, context, nullptr)) {
if (std::find(context.names_return.begin(),
context.names_return.end(),
split_result[0]) == context.names_return.end()) {
std::cerr << "table " << split_result[0] << " not found" << std::endl;
return;
}
} else {
return;
}
context.table_name = split_result[0];
// validate epoch value
try {
context.epoch_value = std::stoi(split_result[1]);
} catch (std::exception& e) {
std::cerr << "non-numeric epoch number: " << table_details << std::endl;
return;
}
if (context.epoch_value < 0) {
std::cerr << "Epoch value can not be negative: " << table_details << std::endl;
return;
}
if (thrift_with_retry(kSET_TABLE_EPOCH_BY_NAME, context, nullptr)) {
std::cout << "table epoch set" << std::endl;
}
}
}
void process_backslash_commands(char* command, ClientContext& context) {
// clang-format off
auto resolution_status = CommandResolutionChain<>( command, "\\h", 1, 1, HelpCmd<>( context ) )
( "\\d", 2, 2, ListColumnsCmd<>( context ), "Usage: \\d <table>" )
( "\\o", 2, 2, GetOptimizedSchemaCmd<>( context ), "Usage: \\o <table>" )
( "\\t", 1, 1, ListTablesCmd<>( context ) )
( "\\v", 1, 1, ListViewsCmd<>( context ) )
( "\\c", 4, 4, ConnectToDBCmd<>( context ), "Usage: \\c <database> <user> <password>" )
( "\\u", 1, 1, ListUsersCmd<>( context ) )
( "\\l", 1, 1, ListDatabasesCmd<>( context ) )
.is_resolved();
if( !resolution_status ) {
std::cerr << "Invalid backslash command: " << command << std::endl;
}
// clang-format on
}
std::string scalar_datum_to_string(const TDatum& datum, const TTypeInfo& type_info) {
constexpr size_t buf_size = 32;
char buf[buf_size]; // Hold "2000-03-01 12:34:56.123456789" and large years.
if (datum.is_null) {
return "NULL";
}
switch (type_info.type) {
case TDatumType::TINYINT:
case TDatumType::SMALLINT:
case TDatumType::INT:
case TDatumType::BIGINT:
return std::to_string(datum.val.int_val);
case TDatumType::DECIMAL: {
std::ostringstream dout;
const auto format_str = "%." + std::to_string(type_info.scale) + "f";
dout << boost::format(format_str) % datum.val.real_val;
return dout.str();
}
case TDatumType::DOUBLE: {
std::ostringstream dout;
dout << std::setprecision(std::numeric_limits<double>::digits10 + 1)
<< datum.val.real_val;
return dout.str();
}
case TDatumType::FLOAT: {
std::ostringstream out;
out << std::setprecision(std::numeric_limits<float>::digits10 + 1)
<< datum.val.real_val;
return out.str();
}
case TDatumType::STR:
return datum.val.str_val;
case TDatumType::TIME: {
size_t const len = shared::formatHMS(buf, buf_size, datum.val.int_val);
CHECK_EQ(8u, len); // 8 == strlen("HH:MM:SS")
return buf;
}
case TDatumType::TIMESTAMP: {
unsigned const dim = type_info.precision; // assumes dim <= 9
size_t const len = shared::formatDateTime(buf, buf_size, datum.val.int_val, dim);
CHECK_LE(19u + bool(dim) + dim, len); // 19 = strlen("YYYY-MM-DD HH:MM:SS")
return buf;
}
case TDatumType::DATE: {
size_t const len = shared::formatDate(buf, buf_size, datum.val.int_val);
CHECK_LE(10u, len); // 10 == strlen("YYYY-MM-DD")
return buf;
}
case TDatumType::BOOL:
return (datum.val.int_val ? "true" : "false");
case TDatumType::INTERVAL_DAY_TIME:
return std::to_string(datum.val.int_val) + " ms (day-time interval)";
case TDatumType::INTERVAL_YEAR_MONTH:
return std::to_string(datum.val.int_val) + " month(s) (year-month interval)";
default:
return "Unknown column type.\n";
}
}
std::string datum_to_string(const TDatum& datum, const TTypeInfo& type_info) {
if (datum.is_null) {
return "NULL";
}
if (type_info.is_array) {
std::vector<std::string> elem_strs;
elem_strs.reserve(datum.val.arr_val.size());
for (const auto& elem_datum : datum.val.arr_val) {
TTypeInfo elem_type_info{type_info};
elem_type_info.is_array = false;
elem_strs.push_back(scalar_datum_to_string(elem_datum, elem_type_info));
}
return "{" + boost::algorithm::join(elem_strs, ", ") + "}";
}
if (type_info.type == TDatumType::POINT || type_info.type == TDatumType::LINESTRING ||
type_info.type == TDatumType::POLYGON ||
type_info.type == TDatumType::MULTIPOLYGON) {
return datum.val.str_val;
}
return scalar_datum_to_string(datum, type_info);
}
TDatum columnar_val_to_datum(const TColumn& col,
const size_t row_idx,
const TTypeInfo& col_type) {
TDatum datum;
if (col_type.is_array) {
auto elem_type = col_type;
elem_type.is_array = false;
datum.is_null = col.nulls[row_idx];
CHECK_LT(row_idx, col.data.arr_col.size());
const auto& arr_col = col.data.arr_col[row_idx];
for (size_t elem_idx = 0; elem_idx < arr_col.nulls.size(); ++elem_idx) {
datum.val.arr_val.push_back(columnar_val_to_datum(arr_col, elem_idx, elem_type));
}
return datum;
}
datum.is_null = col.nulls[row_idx];
switch (col_type.type) {
case TDatumType::TINYINT:
case TDatumType::SMALLINT:
case TDatumType::INT:
case TDatumType::BIGINT:
case TDatumType::TIME:
case TDatumType::TIMESTAMP:
case TDatumType::DATE:
case TDatumType::BOOL:
case TDatumType::INTERVAL_DAY_TIME:
case TDatumType::INTERVAL_YEAR_MONTH: {
datum.val.int_val = col.data.int_col[row_idx];
break;
}
case TDatumType::DECIMAL:
case TDatumType::FLOAT:
case TDatumType::DOUBLE: {
datum.val.real_val = col.data.real_col[row_idx];
break;
}
case TDatumType::STR: {
datum.val.str_val = col.data.str_col[row_idx];
break;
}
case TDatumType::POINT:
case TDatumType::LINESTRING:
case TDatumType::POLYGON:
case TDatumType::MULTIPOLYGON: {
datum.val.str_val = col.data.str_col[row_idx];
break;
}
default:
CHECK(false);
}
return datum;
}
// based on http://www.gnu.org/software/libc/manual/html_node/getpass.html
std::string mapd_getpass() {
#ifndef _WIN32
struct termios origterm, tmpterm;
tcgetattr(STDIN_FILENO, &origterm);
tmpterm = origterm;
tmpterm.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &tmpterm);
#endif
std::cout << "Password: ";
std::string password;
std::getline(std::cin, password);
std::cout << std::endl;
#ifndef _WIN32
tcsetattr(STDIN_FILENO, TCSAFLUSH, &origterm);
#endif
return password;
}
enum Action { INITIALIZE, TURN_ON, TURN_OFF, INTERRUPT };
bool backchannel(int action, ClientContext* cc, const std::string& ccn = "") {
enum State { UNINITIALIZED, INITIALIZED, INTERRUPTIBLE };
static int state = UNINITIALIZED;
static ClientContext* context{nullptr};
static std::string ca_cert_name{};
if (action == INITIALIZE) {
CHECK(cc);
context = cc;
ca_cert_name = ccn;
state = INITIALIZED;
return false;
}
if (state == INITIALIZED && action == TURN_ON) {
state = INTERRUPTIBLE;
return false;
}
if (state == INTERRUPTIBLE && action == TURN_OFF) {
state = INITIALIZED;
return false;
}
if (state == INTERRUPTIBLE && action == INTERRUPT) {
CHECK(context);
std::shared_ptr<ThriftClientConnection> connMgr;
std::shared_ptr<TTransport> transport2;
std::shared_ptr<TProtocol> protocol2;
std::shared_ptr<TTransport> socket2;
connMgr = std::make_shared<ThriftClientConnection>();
if (context->http || context->https) {
transport2 = connMgr->open_http_client_transport(context->server_host,
context->port,
ca_cert_name,
context->https,
context->skip_host_verify);
protocol2 = std::shared_ptr<TProtocol>(new TJSONProtocol(transport2));
} else {
transport2 = connMgr->open_buffered_client_transport(
context->server_host, context->port, ca_cert_name);
protocol2 = std::shared_ptr<TProtocol>(new TBinaryProtocol(transport2));
}
OmniSciClient c2(protocol2);
ClientContext context2(*transport2, c2);
context2.db_name = context->db_name;
context2.user_name = context->user_name;
context2.passwd = context->passwd;
context2.session = INVALID_SESSION_ID;
transport2->open();
if (!transport2->isOpen()) {
std::cout << "Unable to send interrupt to the server.\n" << std::flush;
return false;
}
(void)thrift_with_retry(kCONNECT, context2, nullptr);
std::cout << "Asking server to interrupt query.\n" << std::flush;
(void)thrift_with_retry(kINTERRUPT, context2, nullptr, 1, global_session);
if (context2.session != INVALID_SESSION_ID) {
(void)thrift_with_retry(kDISCONNECT, context2, nullptr);
}
transport2->close();
state = INITIALIZED;
return true;
}
return false;
}
void omnisql_signal_handler(int signal_number) {
std::cout << "\nInterrupt signal (" << signal_number << ") received.\n" << std::flush;
if (backchannel(INTERRUPT, nullptr)) {
return;
}
// terminate program
exit(signal_number);
}
void register_signal_handler() {
signal(SIGTERM, omnisql_signal_handler);
#ifndef _WIN32
signal(SIGKILL, omnisql_signal_handler);
#endif
signal(SIGINT, omnisql_signal_handler);
}
void print_memory_summary(ClientContext& context, std::string memory_level) {
std::ostringstream tss;
std::vector<TNodeMemoryInfo> memory_info;
std::string sub_system;
std::string cur_host = "^";
bool hasGPU = false;
bool multiNode = context.cpu_memory.size() > 1;
if (!memory_level.compare("gpu")) {
memory_info = context.gpu_memory;
sub_system = "GPU";
hasGPU = true;
} else {
memory_info = context.cpu_memory;
sub_system = "CPU";
}
tss << "OmniSci Server " << sub_system << " Memory Summary:" << std::endl;
if (multiNode) {
if (hasGPU) {
tss << " NODE[GPU] MAX USE ALLOCATED "
"FREE"
<< std::endl;
} else {
tss << " NODE MAX USE ALLOCATED FREE"
<< std::endl;
}
} else {
if (hasGPU) {
tss << "[GPU] MAX USE ALLOCATED FREE"
<< std::endl;
} else {
tss << " MAX USE ALLOCATED FREE" << std::endl;
}
}
uint16_t gpu_num = 0;
for (auto& nodeIt : memory_info) {
int MB = 1024 * 1024;
uint64_t page_count = 0;
uint64_t free_page_count = 0;
uint64_t used_page_count = 0;
for (auto& segIt : nodeIt.node_memory_data) {
page_count += segIt.num_pages;
if (segIt.is_free) {
free_page_count += segIt.num_pages;
}
}
if (context.cpu_memory.size() > 1) {
}
used_page_count = page_count - free_page_count;
if (cur_host.compare(nodeIt.host_name)) {
gpu_num = 0;
cur_host = nodeIt.host_name;
} else {
++gpu_num;
}
if (multiNode) {
tss << std::setfill(' ') << std::setw(12) << nodeIt.host_name;
if (hasGPU) {
tss << std::setfill(' ') << std::setw(3);
tss << "[" << gpu_num << "]";
} else {
}
} else {
if (hasGPU) {
tss << std::setfill(' ') << std::setw(3);
tss << "[" << gpu_num << "]";
} else {
}
}
tss << std::fixed;
tss << std::setprecision(2);
tss << std::setfill(' ') << std::setw(12)
<< ((float)nodeIt.page_size * nodeIt.max_num_pages) / MB << " MB";
tss << std::setfill(' ') << std::setw(12)
<< ((float)nodeIt.page_size * used_page_count) / MB << " MB";
tss << std::setfill(' ') << std::setw(12)
<< ((float)nodeIt.page_size * page_count) / MB << " MB";
tss << std::setfill(' ') << std::setw(12)
<< ((float)nodeIt.page_size * free_page_count) / MB << " MB";
if (nodeIt.is_allocation_capped) {
tss << " The allocation is capped!";
}
tss << std::endl;
}
std::cout << tss.str() << std::endl;
}
void print_memory_info(ClientContext& context, std::string memory_level) {
int MB = 1024 * 1024;
std::ostringstream tss;
std::vector<TNodeMemoryInfo> memory_info;
std::string sub_system;
std::string cur_host = "^";
bool multiNode;
int mgr_num = 0;
if (!memory_level.compare("gpu")) {
memory_info = context.gpu_memory;
sub_system = "GPU";
multiNode = context.gpu_memory.size() > 1;
} else {
memory_info = context.cpu_memory;
sub_system = "CPU";
multiNode = context.cpu_memory.size() > 1;
}
tss << "OmniSci Server Detailed " << sub_system << " Memory Usage:" << std::endl;
for (auto& nodeIt : memory_info) {
if (cur_host.compare(nodeIt.host_name)) {
mgr_num = 0;
cur_host = nodeIt.host_name;
if (multiNode) {
tss << "Node: " << nodeIt.host_name << std::endl;
}
tss << "Maximum Bytes for one page: " << nodeIt.page_size << " Bytes" << std::endl;
tss << "Maximum Bytes for node: " << (nodeIt.max_num_pages * nodeIt.page_size) / MB
<< " MB" << std::endl;
tss << "Memory allocated: " << (nodeIt.num_pages_allocated * nodeIt.page_size) / MB
<< " MB" << std::endl;
} else {
++mgr_num;
}
cur_host = nodeIt.host_name;
tss << sub_system << "[" << mgr_num << "]"
<< " Slab Information:" << std::endl;
if (nodeIt.is_allocation_capped) {
tss << "The allocation is capped!";
}
tss << "SLAB ST_PAGE NUM_PAGE TOUCH CHUNK_KEY" << std::endl;
for (auto segIt = nodeIt.node_memory_data.begin();
segIt != nodeIt.node_memory_data.end();
++segIt) {
tss << std::setfill(' ') << std::setw(4) << segIt->slab;
tss << std::setfill(' ') << std::setw(12) << segIt->start_page;
tss << std::setfill(' ') << std::setw(9) << segIt->num_pages;
tss << std::setfill(' ') << std::setw(7) << segIt->touch;
tss << std::setfill(' ') << std::setw(5);
if (segIt->is_free) {
tss << "FREE";
} else {
tss << "USED";
tss << std::setfill(' ') << std::setw(5);
for (auto& vecIt : segIt->chunk_key) {
tss << vecIt << ",";
}
}
tss << std::endl;
}
tss << "---------------------------------------------------------------" << std::endl;
}
std::cout << tss.str() << std::endl;
}
std::string print_gpu_specification(TGpuSpecification gpu_spec) {
int Giga = 1024 * 1024 * 1024;
int Kilo = 1024;
std::ostringstream tss;
tss << "Number of SM :" << gpu_spec.num_sm << std::endl;
tss << "Clock frequency :" << gpu_spec.clock_frequency_kHz / Kilo << " MHz"
<< std::endl;
tss << "Physical GPU Memory :" << gpu_spec.memory / Giga << " GB" << std::endl;
tss << "Compute capability :" << gpu_spec.compute_capability_major << "."
<< gpu_spec.compute_capability_minor << std::endl;
return tss.str();
}
std::string print_hardware_specification(THardwareInfo hw_spec) {
std::ostringstream tss;
if (hw_spec.host_name != "") {
tss << "Host name :" << hw_spec.host_name << std::endl;
}
tss << "Number of Physical GPUs :" << hw_spec.num_gpu_hw << std::endl;
tss << "Number of CPU core :" << hw_spec.num_cpu_hw << std::endl;
tss << "Number of GPUs allocated :" << hw_spec.num_gpu_allocated << std::endl;
tss << "Start GPU :" << hw_spec.start_gpu << std::endl;
for (auto gpu_spec : hw_spec.gpu_info) {
tss << "-------------------------------------------" << std::endl;
tss << print_gpu_specification(gpu_spec);
}
tss << "-------------------------------------------" << std::endl;
return tss.str();
}
void print_all_hardware_info(ClientContext& context) {
std::ostringstream tss;
for (auto hw_info : context.cluster_hardware_info.hardware_info) {
tss << "===========================================" << std::endl;
tss << print_hardware_specification(hw_info) << std::endl;
}
tss << "===========================================" << std::endl;
std::cout << tss.str();
}
static std::vector<std::string> stringify_privs(const std::vector<bool>& priv_mask,
TDBObjectType::type type) {
// Client priviliges print lookup
std::vector<std::string> priv_strs;
static const std::unordered_map<TDBObjectType::type, const std::vector<std::string>>
privilege_names_lookup{
{TDBObjectType::DatabaseDBObjectType,
{"create"s, "drop"s, "view-sql-editor"s, "login-access"s}},
{TDBObjectType::TableDBObjectType,
{"create"s,
"drop"s,
"select"s,
"insert"s,
"update"s,
"delete"s,
"truncate"s,
"alter"s}},
{TDBObjectType::DashboardDBObjectType,
{"create"s, "delete"s, "view"s, "edit"s}},
{TDBObjectType::ViewDBObjectType,
{"create"s, "drop"s, "select"s, "insert"s, "update"s, "delete"s}},
{TDBObjectType::ServerDBObjectType, {"create"s, "drop"s, "alter"s, "usage"s}}};
const auto privilege_names = privilege_names_lookup.find(type);
if (privilege_names != privilege_names_lookup.end()) {
size_t i = 0;
const auto& priv_names = privilege_names->second;
std::copy_if(priv_names.begin(),
priv_names.end(),
std::back_inserter(priv_strs),
[&priv_mask, &i](std::string const& s) { return priv_mask.at(i++); });
}
return priv_strs;
}
namespace {
const size_t priv_col_width = 20;
struct PrivilegeRow {
std::string object_name;
int32_t object_id;
std::string object_type;
std::string privilege_object_type;
std::vector<std::string> privileges;
};
std::ostream& operator<<(std::ostream& os, const PrivilegeRow& priv_row) {
os << std::setw(priv_col_width) << priv_row.object_name;
os << std::setw(priv_col_width) << std::to_string(priv_row.object_id);
os << std::setw(priv_col_width) << priv_row.object_type;
os << std::setw(priv_col_width) << priv_row.privilege_object_type;
os << boost::algorithm::join(priv_row.privileges, ", ");
return os;
};
} // namespace
void get_db_objects_for_grantee(ClientContext& context) {
context.db_objects.clear();
std::ostringstream tss;
tss << std::left << std::setfill(' ');
// NOTE(jclay): At some point, we may want to pull these up into
// a utility for use in omnisql that allows us to easily format and write out tables.
auto write_table_header = [&tss](auto headers) -> void {
for (const auto& h : headers) {
tss << std::setw(priv_col_width);
tss << h;
}
tss << std::endl;
tss << std::string(tss.str().length(), '-') << std::endl;
};
auto write_table_rows = [&tss](std::vector<PrivilegeRow> rows) -> void {
std::sort(
rows.begin(), rows.end(), [](const PrivilegeRow& lhs, const PrivilegeRow& rhs) {
return lhs.object_type < rhs.object_type;
});
tss.width(priv_col_width);
for (const auto& r : rows) {
tss << r;
tss << std::endl;
}
std::cout << tss.str() << std::endl;
};
const std::string object_names[5] = {
"database", "table", "dashboard", "view", "server"};
auto type_to_string = [&](TDBObjectType::type type) -> std::string {
const int type_val = static_cast<int>(type);
CHECK(type_val > 0 && type_val < 6);
return object_names[type_val - 1];
};
const std::vector<std::string> headers = {
"ObjectName", "ObjectId", "ObjectType", "PrivilegeType", "Privileges"};
write_table_header(headers);
if (thrift_with_retry(kGET_OBJECTS_FOR_GRANTEE, context, nullptr)) {
std::vector<PrivilegeRow> table_values;
for (const auto& db_object : context.db_objects) {
PrivilegeRow out_row;
auto has_granted_privs = [](const std::vector<bool>& privs_mask) -> const bool {
return std::accumulate(privs_mask.begin(), privs_mask.end(), 0) > 0;
};
if (!has_granted_privs(db_object.privs)) {
continue;
}
out_row.object_name = db_object.objectName.c_str();
out_row.object_id = db_object.objectId;
out_row.object_type = type_to_string(db_object.objectType);
out_row.privilege_object_type = type_to_string(db_object.privilegeObjectType);
out_row.privileges =
stringify_privs(db_object.privs, db_object.privilegeObjectType);
table_values.push_back(out_row);
}
write_table_rows(table_values);
}
}
void get_db_object_privs(ClientContext& context) {
context.db_objects.clear();
if (thrift_with_retry(kGET_OBJECT_PRIVS, context, nullptr)) {
for (const auto& db_object : context.db_objects) {
if (boost::to_upper_copy<std::string>(context.privs_object_name)
.compare(boost::to_upper_copy<std::string>(db_object.objectName))) {
continue;
}
auto has_granted_privs = [](const std::vector<bool>& privs_mask) -> const bool {
return std::accumulate(privs_mask.begin(), privs_mask.end(), 0) > 0;
};
if (!has_granted_privs(db_object.privs)) {
continue;
}
std::cout << db_object.grantee << " privileges: ";
auto priv_strs = stringify_privs(db_object.privs, db_object.objectType);
std::cout << boost::algorithm::join(priv_strs, ", ");
std::cout << std::endl;
}
}
}
void set_license_key(ClientContext& context, const std::string& token) {
context.license_key = token;
if (thrift_with_retry(kSET_LICENSE_KEY, context, nullptr)) {
for (auto claims : context.license_info.claims) {
std::vector<std::string> jwt;
boost::split(jwt, claims, boost::is_any_of("."));
if (jwt.size() > 1) {
std::cout << shared::decode_base64(jwt[1]) << std::endl;
}
}