-
Notifications
You must be signed in to change notification settings - Fork 968
/
TSServiceImpl.java
1321 lines (1196 loc) · 50.9 KB
/
TSServiceImpl.java
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.iotdb.db.service;
import static org.apache.iotdb.db.conf.IoTDBConstant.COLUMN_PRIVILEGE;
import static org.apache.iotdb.db.conf.IoTDBConstant.COLUMN_ROLE;
import static org.apache.iotdb.db.conf.IoTDBConstant.COLUMN_STORAGE_GROUP;
import static org.apache.iotdb.db.conf.IoTDBConstant.COLUMN_TTL;
import static org.apache.iotdb.db.conf.IoTDBConstant.COLUMN_USER;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.apache.iotdb.db.auth.AuthException;
import org.apache.iotdb.db.auth.AuthorityChecker;
import org.apache.iotdb.db.auth.authorizer.IAuthorizer;
import org.apache.iotdb.db.auth.authorizer.LocalFileAuthorizer;
import org.apache.iotdb.db.conf.IoTDBConfig;
import org.apache.iotdb.db.conf.IoTDBConstant;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
import org.apache.iotdb.db.cost.statistic.Measurement;
import org.apache.iotdb.db.cost.statistic.Operation;
import org.apache.iotdb.db.engine.StorageEngine;
import org.apache.iotdb.db.exception.QueryInBatchStatementException;
import org.apache.iotdb.db.exception.StorageEngineException;
import org.apache.iotdb.db.exception.metadata.MetadataException;
import org.apache.iotdb.db.exception.path.PathException;
import org.apache.iotdb.db.exception.query.QueryProcessException;
import org.apache.iotdb.db.exception.runtime.SQLParserException;
import org.apache.iotdb.db.exception.storageGroup.StorageGroupNotSetException;
import org.apache.iotdb.db.metadata.MManager;
import org.apache.iotdb.db.metrics.server.SqlArgument;
import org.apache.iotdb.db.qp.QueryProcessor;
import org.apache.iotdb.db.qp.constant.SQLConstant;
import org.apache.iotdb.db.qp.executor.QueryProcessExecutor;
import org.apache.iotdb.db.qp.logical.Operator.OperatorType;
import org.apache.iotdb.db.qp.physical.PhysicalPlan;
import org.apache.iotdb.db.qp.physical.crud.BatchInsertPlan;
import org.apache.iotdb.db.qp.physical.crud.DeletePlan;
import org.apache.iotdb.db.qp.physical.crud.InsertPlan;
import org.apache.iotdb.db.qp.physical.crud.QueryPlan;
import org.apache.iotdb.db.qp.physical.sys.AuthorPlan;
import org.apache.iotdb.db.qp.physical.sys.CreateTimeSeriesPlan;
import org.apache.iotdb.db.qp.physical.sys.DeleteStorageGroupPlan;
import org.apache.iotdb.db.qp.physical.sys.DeleteTimeSeriesPlan;
import org.apache.iotdb.db.qp.physical.sys.SetStorageGroupPlan;
import org.apache.iotdb.db.qp.physical.sys.ShowPlan;
import org.apache.iotdb.db.query.context.QueryContext;
import org.apache.iotdb.db.query.control.QueryResourceManager;
import org.apache.iotdb.db.query.dataset.NewEngineDataSetWithoutValueFilter;
import org.apache.iotdb.db.tools.watermark.GroupedLSBWatermarkEncoder;
import org.apache.iotdb.db.tools.watermark.WatermarkEncoder;
import org.apache.iotdb.db.utils.QueryDataSetUtils;
import org.apache.iotdb.rpc.TSStatusCode;
import org.apache.iotdb.service.rpc.thrift.ServerProperties;
import org.apache.iotdb.service.rpc.thrift.TSBatchInsertionReq;
import org.apache.iotdb.service.rpc.thrift.TSCancelOperationReq;
import org.apache.iotdb.service.rpc.thrift.TSCloseOperationReq;
import org.apache.iotdb.service.rpc.thrift.TSCloseSessionReq;
import org.apache.iotdb.service.rpc.thrift.TSCreateTimeseriesReq;
import org.apache.iotdb.service.rpc.thrift.TSDeleteDataReq;
import org.apache.iotdb.service.rpc.thrift.TSExecuteBatchStatementReq;
import org.apache.iotdb.service.rpc.thrift.TSExecuteBatchStatementResp;
import org.apache.iotdb.service.rpc.thrift.TSExecuteInsertRowInBatchResp;
import org.apache.iotdb.service.rpc.thrift.TSExecuteStatementReq;
import org.apache.iotdb.service.rpc.thrift.TSExecuteStatementResp;
import org.apache.iotdb.service.rpc.thrift.TSFetchMetadataReq;
import org.apache.iotdb.service.rpc.thrift.TSFetchMetadataResp;
import org.apache.iotdb.service.rpc.thrift.TSFetchResultsReq;
import org.apache.iotdb.service.rpc.thrift.TSFetchResultsResp;
import org.apache.iotdb.service.rpc.thrift.TSGetTimeZoneResp;
import org.apache.iotdb.service.rpc.thrift.TSIService;
import org.apache.iotdb.service.rpc.thrift.TSInsertInBatchReq;
import org.apache.iotdb.service.rpc.thrift.TSInsertReq;
import org.apache.iotdb.service.rpc.thrift.TSOpenSessionReq;
import org.apache.iotdb.service.rpc.thrift.TSOpenSessionResp;
import org.apache.iotdb.service.rpc.thrift.TSProtocolVersion;
import org.apache.iotdb.service.rpc.thrift.TSQueryDataSet;
import org.apache.iotdb.service.rpc.thrift.TSSetTimeZoneReq;
import org.apache.iotdb.service.rpc.thrift.TSStatus;
import org.apache.iotdb.service.rpc.thrift.TSStatusType;
import org.apache.iotdb.tsfile.exception.filter.QueryFilterOptimizationException;
import org.apache.iotdb.tsfile.exception.write.UnSupportedDataTypeException;
import org.apache.iotdb.tsfile.file.metadata.enums.CompressionType;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
import org.apache.iotdb.tsfile.read.common.Path;
import org.apache.iotdb.tsfile.read.query.dataset.QueryDataSet;
import org.apache.thrift.TException;
import org.apache.thrift.server.ServerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Thrift RPC implementation at server side.
*/
public class TSServiceImpl implements TSIService.Iface, ServerContext {
private static final Logger logger = LoggerFactory.getLogger(TSServiceImpl.class);
private static final String INFO_NOT_LOGIN = "{}: Not login.";
private static final int MAX_SIZE = 200;
private static final int DELETE_SIZE = 50;
private static final String ERROR_PARSING_SQL = "meet error while parsing SQL to physical plan: {}";
public static Vector<SqlArgument> sqlArgumentsList = new Vector<>();
protected QueryProcessor processor;
// Record the username for every rpc connection (session).
private Map<Long, String> sessionIdUsernameMap = new ConcurrentHashMap<>();
private Map<Long, ZoneId> sessionIdZoneIdMap = new ConcurrentHashMap<>();
// The sessionId is unique in one IoTDB instance.
private AtomicLong sessionIdGenerator = new AtomicLong();
// The statementId is unique in one IoTDB instance.
private AtomicLong statementIdGenerator = new AtomicLong();
// (sessionId -> Set(statementId))
private Map<Long, Set<Long>> sessionId2StatementId = new ConcurrentHashMap<>();
// (statementId -> Set(queryId))
private Map<Long, Set<Long>> statementId2QueryId = new ConcurrentHashMap<>();
// (queryId -> QueryDataSet)
private Map<Long, QueryDataSet> queryId2DataSet = new ConcurrentHashMap<>();
private IoTDBConfig config = IoTDBDescriptor.getInstance().getConfig();
// When the client abnormally exits, we can still know who to disconnect
private ThreadLocal<Long> currSessionId = new ThreadLocal<>();
public TSServiceImpl() {
processor = new QueryProcessor(new QueryProcessExecutor());
}
public static TSDataType getSeriesType(String path) throws QueryProcessException {
switch (path.toLowerCase()) {
// authorization queries
case COLUMN_ROLE:
case COLUMN_USER:
case COLUMN_PRIVILEGE:
case COLUMN_STORAGE_GROUP:
return TSDataType.TEXT;
case COLUMN_TTL:
return TSDataType.INT64;
default:
// do nothing
}
if (path.contains("(") && !path.startsWith("(") && path.endsWith(")")) {
// aggregation
int leftBracketIndex = path.indexOf('(');
String aggrType = path.substring(0, leftBracketIndex);
String innerPath = path.substring(leftBracketIndex + 1, path.length() - 1);
switch (aggrType.toLowerCase()) {
case SQLConstant.MIN_TIME:
case SQLConstant.MAX_TIME:
case SQLConstant.COUNT:
return TSDataType.INT64;
case SQLConstant.LAST_VALUE:
case SQLConstant.FIRST_VALUE:
case SQLConstant.MIN_VALUE:
case SQLConstant.MAX_VALUE:
return getSeriesType(innerPath);
case SQLConstant.AVG:
case SQLConstant.SUM:
return TSDataType.DOUBLE;
default:
throw new QueryProcessException(
"aggregate does not support " + aggrType + " function.");
}
}
return MManager.getInstance().getSeriesType(path);
}
@Override
public TSOpenSessionResp openSession(TSOpenSessionReq req) throws TException {
logger.info("{}: receive open session request from username {}", IoTDBConstant.GLOBAL_DB_NAME,
req.getUsername());
boolean status;
IAuthorizer authorizer;
try {
authorizer = LocalFileAuthorizer.getInstance();
} catch (AuthException e) {
throw new TException(e);
}
try {
status = authorizer.login(req.getUsername(), req.getPassword());
} catch (AuthException e) {
logger.info("meet error while logging in.", e);
status = false;
}
TSStatus tsStatus;
long sessionId = -1;
if (status) {
tsStatus = getStatus(TSStatusCode.SUCCESS_STATUS, "Login successfully");
sessionId = sessionIdGenerator.incrementAndGet();
sessionIdUsernameMap.put(sessionId, req.getUsername());
sessionIdZoneIdMap.put(sessionId, config.getZoneID());
currSessionId.set(sessionId);
} else {
tsStatus = getStatus(TSStatusCode.WRONG_LOGIN_PASSWORD_ERROR);
}
TSOpenSessionResp resp = new TSOpenSessionResp(tsStatus,
TSProtocolVersion.IOTDB_SERVICE_PROTOCOL_V1);
resp.setSessionId(sessionId);
logger.info("{}: Login status: {}. User : {}", IoTDBConstant.GLOBAL_DB_NAME,
tsStatus.getStatusType().getMessage(), req.getUsername());
return resp;
}
@Override
public TSStatus closeSession(TSCloseSessionReq req) {
logger.info("{}: receive close session", IoTDBConstant.GLOBAL_DB_NAME);
long sessionId = req.getSessionId();
TSStatus tsStatus;
if (sessionIdUsernameMap.remove(sessionId) == null) {
tsStatus = getStatus(TSStatusCode.NOT_LOGIN_ERROR);
} else {
tsStatus = getStatus(TSStatusCode.SUCCESS_STATUS);
}
sessionIdZoneIdMap.remove(sessionId);
List<Exception> exceptions = new ArrayList<>();
Set<Long> statementIds = sessionId2StatementId.getOrDefault(sessionId, Collections.emptySet());
for (long statementId : statementIds) {
Set<Long> queryIds = statementId2QueryId.getOrDefault(statementId, Collections.emptySet());
for (long queryId : queryIds) {
queryId2DataSet.remove(queryId);
try {
QueryResourceManager.getInstance().endQuery(queryId);
} catch (StorageEngineException e) {
// release as many as resources as possible, so do not break as soon as one exception is
// raised
exceptions.add(e);
logger.error("Error in closeSession : ", e);
}
}
}
if (!exceptions.isEmpty()) {
return new TSStatus(
getStatus(TSStatusCode.CLOSE_OPERATION_ERROR,
String.format("%d errors in closeOperation, see server logs for detail",
exceptions.size())));
}
return new TSStatus(tsStatus);
}
@Override
public TSStatus cancelOperation(TSCancelOperationReq req) {
//TODO implement
return getStatus(TSStatusCode.QUERY_NOT_ALLOWED, "Cancellation is not implemented");
}
@Override
public TSStatus closeOperation(TSCloseOperationReq req) {
logger.info("{}: receive close operation", IoTDBConstant.GLOBAL_DB_NAME);
if (!checkLogin(req.getSessionId())) {
logger.info(INFO_NOT_LOGIN, IoTDBConstant.GLOBAL_DB_NAME);
return getStatus(TSStatusCode.NOT_LOGIN_ERROR);
}
try {
// statement close
if (req.isSetStatementId()) {
long stmtId = req.getStatementId();
Set<Long> queryIdSet = statementId2QueryId.remove(stmtId);
if (queryIdSet != null) {
for (long queryId : queryIdSet) {
releaseQueryResource(queryId);
}
}
} else {
// ResultSet close
releaseQueryResource(req.queryId);
}
} catch (Exception e) {
logger.error("Error in closeOperation : ", e);
return getStatus(TSStatusCode.CLOSE_OPERATION_ERROR, "Error in closeOperation");
}
return getStatus(TSStatusCode.SUCCESS_STATUS);
}
/**
* release single operation resource
*/
private void releaseQueryResource(long queryId) throws StorageEngineException {
// remove the corresponding Physical Plan
queryId2DataSet.remove(queryId);
QueryResourceManager.getInstance().endQuery(queryId);
}
/**
* convert from TSStatusCode to TSStatus according to status code and status message
*
* @param statusType status type
*/
static TSStatus getStatus(TSStatusCode statusType) {
TSStatusType statusCodeAndMessage = new TSStatusType(statusType.getStatusCode(), "");
return new TSStatus(statusCodeAndMessage);
}
/**
* convert from TSStatusCode to TSStatus, which has message appending with existed status message
*
* @param statusType status type
* @param appendMessage appending message
*/
private TSStatus getStatus(TSStatusCode statusType, String appendMessage) {
TSStatusType statusCodeAndMessage = new TSStatusType(statusType.getStatusCode(), appendMessage);
return new TSStatus(statusCodeAndMessage);
}
@Override
public TSFetchMetadataResp fetchMetadata(TSFetchMetadataReq req) {
TSStatus status;
if (!checkLogin(req.getSessionId())) {
logger.info(INFO_NOT_LOGIN, IoTDBConstant.GLOBAL_DB_NAME);
status = getStatus(TSStatusCode.NOT_LOGIN_ERROR);
return new TSFetchMetadataResp(status);
}
TSFetchMetadataResp resp = new TSFetchMetadataResp();
try {
switch (req.getType()) {
case "SHOW_TIMESERIES":
String path = req.getColumnPath();
List<List<String>> timeseriesList = getTimeSeriesForPath(path);
resp.setTimeseriesList(timeseriesList);
status = getStatus(TSStatusCode.SUCCESS_STATUS);
break;
case "SHOW_STORAGE_GROUP":
Set<String> storageGroups = new HashSet<>(getAllStorageGroups());
resp.setStorageGroups(storageGroups);
status = getStatus(TSStatusCode.SUCCESS_STATUS);
break;
case "METADATA_IN_JSON":
String metadataInJson = getMetadataInString();
resp.setMetadataInJson(metadataInJson);
status = getStatus(TSStatusCode.SUCCESS_STATUS);
break;
case "SHOW_DEVICES":
Set<String> devices = getAllDevices();
resp.setDevices(devices);
status = getStatus(TSStatusCode.SUCCESS_STATUS);
break;
case "SHOW_CHILD_PATHS":
path = req.getColumnPath();
Set<String> childPaths = getChildPaths(path);
resp.setChildPaths(childPaths);
status = getStatus(TSStatusCode.SUCCESS_STATUS);
break;
case "COLUMN":
resp.setDataType(getSeriesType(req.getColumnPath()).toString());
status = getStatus(TSStatusCode.SUCCESS_STATUS);
break;
case "ALL_COLUMNS":
resp.setColumnsList(getPaths(req.getColumnPath()));
status = getStatus(TSStatusCode.SUCCESS_STATUS);
break;
case "COUNT_TIMESERIES":
resp.setTimeseriesNum(getPaths(req.getColumnPath()).size());
status = getStatus(TSStatusCode.SUCCESS_STATUS);
break;
case "COUNT_NODES":
resp.setNodesList(getNodesList(req.getColumnPath(), req.getNodeLevel()));
status = getStatus(TSStatusCode.SUCCESS_STATUS);
break;
case "COUNT_NODE_TIMESERIES":
resp.setNodeTimeseriesNum(
getNodeTimeseriesNum(getNodesList(req.getColumnPath(), req.getNodeLevel())));
status = getStatus(TSStatusCode.SUCCESS_STATUS);
break;
default:
status = getStatus(TSStatusCode.METADATA_ERROR, req.getType());
break;
}
} catch (QueryProcessException | MetadataException | OutOfMemoryError | SQLException e) {
logger
.error(String.format("Failed to fetch timeseries %s's metadata", req.getColumnPath()), e);
status = getStatus(TSStatusCode.METADATA_ERROR, e.getMessage());
resp.setStatus(status);
return resp;
}
resp.setStatus(status);
return resp;
}
private Map<String, String> getNodeTimeseriesNum(List<String> nodes)
throws MetadataException {
Map<String, String> nodeColumnsNum = new HashMap<>();
for (String columnPath : nodes) {
nodeColumnsNum.put(columnPath, Integer.toString(getPaths(columnPath).size()));
}
return nodeColumnsNum;
}
private List<String> getNodesList(String schemaPattern, int level) throws SQLException {
return MManager.getInstance().getNodesList(schemaPattern, level);
}
private List<String> getAllStorageGroups() {
return MManager.getInstance().getAllStorageGroupNames();
}
private Set<String> getAllDevices() throws SQLException {
return MManager.getInstance().getAllDevices();
}
private Set<String> getChildPaths(String path) throws PathException {
return MManager.getInstance().getChildNodePathInNextLevel(path);
}
private List<List<String>> getTimeSeriesForPath(String path)
throws PathException {
return MManager.getInstance().getShowTimeseriesPath(path);
}
private String getMetadataInString() {
return MManager.getInstance().getMetadataInString();
}
protected List<String> getPaths(String path) throws MetadataException {
return MManager.getInstance().getPaths(path);
}
/**
* Judge whether the statement is ADMIN COMMAND and if true, execute it.
*
* @param statement command
* @return true if the statement is ADMIN COMMAND
*/
private boolean execAdminCommand(String statement, long sessionId) throws StorageEngineException {
if (!"root".equals(sessionIdUsernameMap.get(sessionId))) {
return false;
}
if (statement == null) {
return false;
}
statement = statement.toLowerCase();
if (statement.startsWith("flush")) {
try {
execFlush(statement);
} catch (StorageGroupNotSetException e) {
throw new StorageEngineException(e);
}
return true;
}
switch (statement) {
case "merge":
StorageEngine.getInstance()
.mergeAll(IoTDBDescriptor.getInstance().getConfig().isForceFullMerge());
return true;
case "full merge":
StorageEngine.getInstance().mergeAll(true);
return true;
default:
return false;
}
}
private void execFlush(String statement) throws StorageGroupNotSetException {
String[] args = statement.split("\\s+");
if (args.length == 1) {
StorageEngine.getInstance().syncCloseAllProcessor();
} else if (args.length == 2){
String[] storageGroups = args[1].split(",");
for (String storageGroup : storageGroups) {
StorageEngine.getInstance().asyncCloseProcessor(storageGroup, true);
StorageEngine.getInstance().asyncCloseProcessor(storageGroup, false);
}
} else {
String[] storageGroups = args[1].split(",");
boolean isSeq = Boolean.parseBoolean(args[2]);
for (String storageGroup : storageGroups) {
StorageEngine.getInstance().asyncCloseProcessor(storageGroup, isSeq);
}
}
}
@Override
public TSExecuteBatchStatementResp executeBatchStatement(TSExecuteBatchStatementReq req) {
long t1 = System.currentTimeMillis();
List<Integer> result = new ArrayList<>();
try {
if (!checkLogin(req.getSessionId())) {
logger.info(INFO_NOT_LOGIN, IoTDBConstant.GLOBAL_DB_NAME);
return getTSBatchExecuteStatementResp(getStatus(TSStatusCode.NOT_LOGIN_ERROR), null);
}
List<String> statements = req.getStatements();
boolean isAllSuccessful = true;
StringBuilder batchErrorMessage = new StringBuilder();
for (String statement : statements) {
long t2 = System.currentTimeMillis();
isAllSuccessful =
isAllSuccessful && executeStatementInBatch(statement, batchErrorMessage, result,
req.getSessionId());
Measurement.INSTANCE.addOperationLatency(Operation.EXECUTE_ONE_SQL_IN_BATCH, t2);
}
if (isAllSuccessful) {
return getTSBatchExecuteStatementResp(getStatus(TSStatusCode.SUCCESS_STATUS,
"Execute batch statements successfully"), result);
} else {
return getTSBatchExecuteStatementResp(getStatus(TSStatusCode.EXECUTE_STATEMENT_ERROR,
batchErrorMessage.toString()), result);
}
} finally {
Measurement.INSTANCE.addOperationLatency(Operation.EXECUTE_JDBC_BATCH, t1);
}
}
// execute one statement of a batch. Currently, query is not allowed in a batch statement and
// on finding queries in a batch, such query will be ignored and an error will be generated
private boolean executeStatementInBatch(String statement, StringBuilder batchErrorMessage,
List<Integer> result, long sessionId) {
try {
PhysicalPlan physicalPlan = processor
.parseSQLToPhysicalPlan(statement, sessionIdZoneIdMap.get(sessionId));
if (physicalPlan.isQuery()) {
throw new QueryInBatchStatementException(statement);
}
TSExecuteStatementResp resp = executeUpdateStatement(physicalPlan, sessionId);
if (resp.getStatus().getStatusType().getCode() == TSStatusCode.SUCCESS_STATUS
.getStatusCode()) {
result.add(Statement.SUCCESS_NO_INFO);
} else {
result.add(Statement.EXECUTE_FAILED);
batchErrorMessage.append(resp.getStatus().getStatusType().getCode()).append("\n");
return false;
}
} catch (ParseCancellationException e) {
logger.debug(e.getMessage());
result.add(Statement.EXECUTE_FAILED);
batchErrorMessage.append(TSStatusCode.SQL_PARSE_ERROR.getStatusCode()).append("\n");
return false;
} catch (SQLParserException e) {
logger.error("Error occurred when executing {}, check metadata error: ", statement, e);
result.add(Statement.EXECUTE_FAILED);
batchErrorMessage.append(TSStatusCode.METADATA_ERROR.getStatusCode()).append("\n");
return false;
} catch (QueryProcessException e) {
logger.info(
"Error occurred when executing {}, meet error while parsing SQL to physical plan: {}",
statement, e.getMessage());
result.add(Statement.EXECUTE_FAILED);
batchErrorMessage.append(TSStatusCode.SQL_PARSE_ERROR.getStatusCode()).append("\n");
return false;
} catch (QueryInBatchStatementException e) {
logger.info("Error occurred when executing {}, query statement not allowed: ", statement, e);
result.add(Statement.EXECUTE_FAILED);
batchErrorMessage.append(TSStatusCode.QUERY_NOT_ALLOWED.getStatusCode()).append("\n");
return false;
}
return true;
}
@Override
public TSExecuteStatementResp executeStatement(TSExecuteStatementReq req) {
long startTime = System.currentTimeMillis();
TSExecuteStatementResp resp;
SqlArgument sqlArgument;
try {
if (!checkLogin(req.getSessionId())) {
logger.info(INFO_NOT_LOGIN, IoTDBConstant.GLOBAL_DB_NAME);
return getTSExecuteStatementResp(getStatus(TSStatusCode.NOT_LOGIN_ERROR));
}
String statement = req.getStatement();
if (execAdminCommand(statement, req.getSessionId())) {
return getTSExecuteStatementResp(
getStatus(TSStatusCode.SUCCESS_STATUS, "ADMIN_COMMAND_SUCCESS"));
}
PhysicalPlan physicalPlan = processor.parseSQLToPhysicalPlan(statement,
sessionIdZoneIdMap.get(req.getSessionId()));
if (physicalPlan.isQuery()) {
resp = executeQueryStatement(req.statementId, physicalPlan, req.fetchSize,
sessionIdUsernameMap.get(req.getSessionId()));
long endTime = System.currentTimeMillis();
sqlArgument = new SqlArgument(resp, physicalPlan, statement, startTime, endTime);
sqlArgumentsList.add(sqlArgument);
if (sqlArgumentsList.size() > MAX_SIZE) {
sqlArgumentsList.subList(0, DELETE_SIZE).clear();
}
return resp;
} else {
return executeUpdateStatement(physicalPlan, req.getSessionId());
}
} catch (ParseCancellationException e) {
logger.debug(e.getMessage());
return getTSExecuteStatementResp(getStatus(TSStatusCode.SQL_PARSE_ERROR, e.getMessage()));
} catch (SQLParserException e) {
logger.error("check metadata error: ", e);
return getTSExecuteStatementResp(getStatus(TSStatusCode.METADATA_ERROR,
"Check metadata error: " + e.getMessage()));
} catch (QueryProcessException e) {
logger.info(ERROR_PARSING_SQL, e.getMessage());
return getTSExecuteStatementResp(getStatus(TSStatusCode.SQL_PARSE_ERROR,
"Statement format is not right: " + e.getMessage()));
} catch (StorageEngineException e) {
logger.info(ERROR_PARSING_SQL, e.getMessage());
return getTSExecuteStatementResp(getStatus(TSStatusCode.READ_ONLY_SYSTEM_ERROR,
e.getMessage()));
}
}
/**
* @param plan must be a plan for Query: FillQueryPlan, AggregationPlan, GroupByPlan, some
* AuthorPlan
*/
private TSExecuteStatementResp executeQueryStatement(long statementId, PhysicalPlan plan,
int fetchSize, String username) {
long t1 = System.currentTimeMillis();
try {
TSExecuteStatementResp resp; // column headers
if (plan instanceof AuthorPlan) {
resp = getAuthQueryColumnHeaders(plan);
} else if (plan instanceof ShowPlan) {
resp = getShowQueryColumnHeaders((ShowPlan) plan);
} else {
resp = getQueryColumnHeaders(plan, username);
}
if (plan.getOperatorType() == OperatorType.AGGREGATION) {
resp.setIgnoreTimeStamp(true);
} // else default ignoreTimeStamp is false
resp.setOperationType(plan.getOperatorType().toString());
// generate the queryId for the operation
long queryId = generateQueryId(true);
// put it into the corresponding Set
statementId2QueryId.computeIfAbsent(statementId, k -> new HashSet<>()).add(queryId);
// create and cache dataset
QueryDataSet newDataSet = createQueryDataSet(queryId, plan);
TSQueryDataSet result = fillRpcReturnData(fetchSize, newDataSet, username);
resp.setQueryDataSet(result);
resp.setQueryId(queryId);
return resp;
} catch (Exception e) {
logger.error("{}: Internal server error: ", IoTDBConstant.GLOBAL_DB_NAME, e);
return getTSExecuteStatementResp(
getStatus(TSStatusCode.INTERNAL_SERVER_ERROR, e.getMessage()));
} finally {
Measurement.INSTANCE.addOperationLatency(Operation.EXECUTE_QUERY, t1);
}
}
@Override
public TSExecuteStatementResp executeQueryStatement(TSExecuteStatementReq req) {
if (!checkLogin(req.getSessionId())) {
logger.info(INFO_NOT_LOGIN, IoTDBConstant.GLOBAL_DB_NAME);
return getTSExecuteStatementResp(getStatus(TSStatusCode.NOT_LOGIN_ERROR));
}
String statement = req.getStatement();
PhysicalPlan physicalPlan;
try {
physicalPlan = processor
.parseSQLToPhysicalPlan(statement, sessionIdZoneIdMap.get(req.getSessionId()));
} catch (QueryProcessException | SQLParserException e) {
logger.info(ERROR_PARSING_SQL, e.getMessage());
return getTSExecuteStatementResp(getStatus(TSStatusCode.SQL_PARSE_ERROR, e.getMessage()));
}
if (!physicalPlan.isQuery()) {
return getTSExecuteStatementResp(getStatus(TSStatusCode.EXECUTE_STATEMENT_ERROR,
"Statement is not a query statement."));
}
return executeQueryStatement(req.statementId, physicalPlan, req.fetchSize,
sessionIdUsernameMap.get(req.getSessionId()));
}
private TSExecuteStatementResp getShowQueryColumnHeaders(ShowPlan showPlan)
throws QueryProcessException {
switch (showPlan.getShowContentType()) {
case TTL:
return StaticResps.TTL_RESP;
case FLUSH_TASK_INFO:
return StaticResps.FLUSH_INFO_RESP;
case DYNAMIC_PARAMETER:
return StaticResps.DYNAMIC_PARAMETER_RESP;
case VERSION:
return StaticResps.SHOW_VERSION_RESP;
default:
logger.error("Unsupported show content type: {}", showPlan.getShowContentType());
throw new QueryProcessException(
"Unsupported show content type:" + showPlan.getShowContentType());
}
}
private TSExecuteStatementResp getAuthQueryColumnHeaders(PhysicalPlan plan) {
AuthorPlan authorPlan = (AuthorPlan) plan;
switch (authorPlan.getAuthorType()) {
case LIST_ROLE:
case LIST_USER_ROLES:
return StaticResps.LIST_ROLE_RESP;
case LIST_USER:
case LIST_ROLE_USERS:
return StaticResps.LIST_USER_RESP;
case LIST_ROLE_PRIVILEGE:
return StaticResps.LIST_ROLE_PRIVILEGE_RESP;
case LIST_USER_PRIVILEGE:
return StaticResps.LIST_USER_PRIVILEGE_RESP;
default:
return getTSExecuteStatementResp(getStatus(TSStatusCode.SQL_PARSE_ERROR,
String.format("%s is not an auth query", authorPlan.getAuthorType())));
}
}
/**
* get ResultSet schema
*/
private TSExecuteStatementResp getQueryColumnHeaders(PhysicalPlan physicalPlan, String username)
throws AuthException, TException, QueryProcessException {
List<String> respColumns = new ArrayList<>();
List<String> columnsTypes = new ArrayList<>();
// check permissions
if (!checkAuthorization(physicalPlan.getPaths(), physicalPlan, username)) {
return getTSExecuteStatementResp(getStatus(TSStatusCode.NO_PERMISSION_ERROR,
"No permissions for this operation " + physicalPlan.getOperatorType()));
}
TSExecuteStatementResp resp = getTSExecuteStatementResp(getStatus(TSStatusCode.SUCCESS_STATUS));
// group by device query
QueryPlan plan = (QueryPlan) physicalPlan;
if (plan.isGroupByDevice()) {
getGroupByDeviceQueryHeaders(plan, respColumns, columnsTypes);
// set dataTypeList in TSExecuteStatementResp. Note this is without deduplication.
resp.setColumns(respColumns);
resp.setDataTypeList(columnsTypes);
} else {
getWideQueryHeaders(plan, respColumns, columnsTypes);
resp.setColumns(respColumns);
resp.setDataTypeList(columnsTypes);
}
return resp;
}
// wide means not group by device
private void getWideQueryHeaders(QueryPlan plan, List<String> respColumns,
List<String> columnTypes) throws TException, QueryProcessException {
// Restore column header of aggregate to func(column_name), only
// support single aggregate function for now
List<Path> paths = plan.getPaths();
switch (plan.getOperatorType()) {
case QUERY:
case FILL:
for (Path p : paths) {
respColumns.add(p.getFullPath());
}
break;
case AGGREGATION:
case GROUPBY:
List<String> aggregations = plan.getAggregations();
if (aggregations.size() != paths.size()) {
for (int i = 1; i < paths.size(); i++) {
aggregations.add(aggregations.get(0));
}
}
for (int i = 0; i < paths.size(); i++) {
respColumns.add(aggregations.get(i) + "(" + paths.get(i).getFullPath() + ")");
}
break;
default:
throw new TException("unsupported query type: " + plan.getOperatorType());
}
for (String column : respColumns) {
columnTypes.add(getSeriesType(column).toString());
}
}
private void getGroupByDeviceQueryHeaders(QueryPlan plan, List<String> respColumns,
List<String> columnTypes) {
// set columns in TSExecuteStatementResp. Note this is without deduplication.
List<String> measurementColumns = plan.getMeasurementColumnList();
respColumns.add(SQLConstant.GROUPBY_DEVICE_COLUMN_NAME);
respColumns.addAll(measurementColumns);
// get column types and do deduplication
columnTypes.add(TSDataType.TEXT.toString()); // the DEVICE column of GROUP_BY_DEVICE result
List<TSDataType> deduplicatedColumnsType = new ArrayList<>();
deduplicatedColumnsType.add(TSDataType.TEXT); // the DEVICE column of GROUP_BY_DEVICE result
List<String> deduplicatedMeasurementColumns = new ArrayList<>();
Set<String> tmpColumnSet = new HashSet<>();
Map<String, TSDataType> checker = plan.getDataTypeConsistencyChecker();
for (String column : measurementColumns) {
TSDataType dataType = checker.get(column);
columnTypes.add(dataType.toString());
if (!tmpColumnSet.contains(column)) {
// Note that this deduplication strategy is consistent with that of client IoTDBQueryResultSet.
tmpColumnSet.add(column);
deduplicatedMeasurementColumns.add(column);
deduplicatedColumnsType.add(dataType);
}
}
// save deduplicated measurementColumn names and types in QueryPlan for the next stage to use.
// i.e., used by DeviceIterateDataSet constructor in `fetchResults` stage.
plan.setMeasurementColumnList(deduplicatedMeasurementColumns);
plan.setDataTypes(deduplicatedColumnsType);
// set these null since they are never used henceforth in GROUP_BY_DEVICE query processing.
plan.setPaths(null);
plan.setDataTypeConsistencyChecker(null);
}
@Override
public TSFetchResultsResp fetchResults(TSFetchResultsReq req) {
try {
if (!checkLogin(req.getSessionId())) {
return getTSFetchResultsResp(getStatus(TSStatusCode.NOT_LOGIN_ERROR));
}
if (!queryId2DataSet.containsKey(req.queryId)) {
return getTSFetchResultsResp(
getStatus(TSStatusCode.EXECUTE_STATEMENT_ERROR, "Has not executed query"));
}
QueryDataSet queryDataSet = queryId2DataSet.get(req.queryId);
TSQueryDataSet result = fillRpcReturnData(req.fetchSize, queryDataSet,
sessionIdUsernameMap.get(req.sessionId));
boolean hasResultSet = result.bufferForTime().limit() != 0;
if (!hasResultSet) {
queryId2DataSet.remove(req.queryId);
}
TSFetchResultsResp resp = getTSFetchResultsResp(getStatus(TSStatusCode.SUCCESS_STATUS,
"FetchResult successfully. Has more result: " + hasResultSet));
resp.setHasResultSet(hasResultSet);
resp.setQueryDataSet(result);
return resp;
} catch (Exception e) {
logger.error("{}: Internal server error: ", IoTDBConstant.GLOBAL_DB_NAME, e);
return getTSFetchResultsResp(getStatus(TSStatusCode.INTERNAL_SERVER_ERROR, e.getMessage()));
}
}
private TSQueryDataSet fillRpcReturnData(int fetchSize, QueryDataSet queryDataSet,
String userName)
throws TException, AuthException, IOException {
IAuthorizer authorizer;
try {
authorizer = LocalFileAuthorizer.getInstance();
} catch (AuthException e) {
throw new TException(e);
}
TSQueryDataSet result;
if (config.isEnableWatermark() && authorizer.isUserUseWaterMark(userName)) {
WatermarkEncoder encoder;
if (config.getWatermarkMethodName().equals(IoTDBConfig.WATERMARK_GROUPED_LSB)) {
encoder = new GroupedLSBWatermarkEncoder(config);
} else {
throw new UnSupportedDataTypeException(String.format(
"Watermark method is not supported yet: %s", config.getWatermarkMethodName()));
}
if (queryDataSet instanceof NewEngineDataSetWithoutValueFilter) {
// optimize for query without value filter
result = ((NewEngineDataSetWithoutValueFilter) queryDataSet).fillBuffer(fetchSize, encoder);
} else {
result = QueryDataSetUtils.convertQueryDataSetByFetchSize(queryDataSet, fetchSize, encoder);
}
} else {
if (queryDataSet instanceof NewEngineDataSetWithoutValueFilter) {
// optimize for query without value filter
result = ((NewEngineDataSetWithoutValueFilter) queryDataSet).fillBuffer(fetchSize, null);
} else {
result = QueryDataSetUtils.convertQueryDataSetByFetchSize(queryDataSet, fetchSize);
}
}
return result;
}
/**
* create QueryDataSet and buffer it for fetchResults
*/
private QueryDataSet createQueryDataSet(long queryId, PhysicalPlan physicalPlan) throws
QueryProcessException, QueryFilterOptimizationException, StorageEngineException, IOException {
QueryContext context = new QueryContext(queryId);
QueryDataSet queryDataSet = processor.getExecutor().processQuery(physicalPlan, context);
queryId2DataSet.put(queryId, queryDataSet);
return queryDataSet;
}
@Override
public TSExecuteStatementResp executeUpdateStatement(TSExecuteStatementReq req) {
try {
if (!checkLogin(req.getSessionId())) {
logger.info(INFO_NOT_LOGIN, IoTDBConstant.GLOBAL_DB_NAME);
return getTSExecuteStatementResp(getStatus(TSStatusCode.NOT_LOGIN_ERROR));
}
String statement = req.getStatement();
return executeUpdateStatement(statement, req.getSessionId());
} catch (Exception e) {
logger.error("{}: server Internal Error: ", IoTDBConstant.GLOBAL_DB_NAME, e);
return getTSExecuteStatementResp(
getStatus(TSStatusCode.INTERNAL_SERVER_ERROR, e.getMessage()));
}
}
private TSExecuteStatementResp executeUpdateStatement(PhysicalPlan plan, long sessionId) {
TSStatus status = checkAuthority(plan, sessionId);
if (status != null) {
return new TSExecuteStatementResp(status);
}
status = executePlan(plan);
TSExecuteStatementResp resp = getTSExecuteStatementResp(status);
long queryId = generateQueryId(false);
resp.setQueryId(queryId);
return resp;
}
private boolean executeNonQuery(PhysicalPlan plan) throws QueryProcessException {
if (IoTDBDescriptor.getInstance().getConfig().isReadOnly()) {
throw new QueryProcessException(
"Current system mode is read-only, does not support non-query operation");
}
return processor.getExecutor().processNonQuery(plan);
}
private TSExecuteStatementResp executeUpdateStatement(String statement, long sessionId) {
PhysicalPlan physicalPlan;
try {
physicalPlan = processor.parseSQLToPhysicalPlan(statement, sessionIdZoneIdMap.get(sessionId));
} catch (QueryProcessException | SQLParserException e) {
logger.info(ERROR_PARSING_SQL, e.getMessage());
return getTSExecuteStatementResp(getStatus(TSStatusCode.SQL_PARSE_ERROR, e.getMessage()));
}
if (physicalPlan.isQuery()) {
return getTSExecuteStatementResp(getStatus(TSStatusCode.EXECUTE_STATEMENT_ERROR,
"Statement is a query statement."));
}
return executeUpdateStatement(physicalPlan, sessionId);
}
/**
* Check whether current user has logged in.
*
* @return true: If logged in; false: If not logged in
*/
private boolean checkLogin(long sessionId) {
return sessionIdUsernameMap.get(sessionId) != null;
}
private boolean checkAuthorization(List<Path> paths, PhysicalPlan plan, String username)
throws AuthException {
String targetUser = null;
if (plan instanceof AuthorPlan) {
targetUser = ((AuthorPlan) plan).getUserName();
}
return AuthorityChecker.check(username, paths, plan.getOperatorType(), targetUser);
}