-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSessionPool.cs
More file actions
1836 lines (1609 loc) · 76.6 KB
/
SessionPool.cs
File metadata and controls
1836 lines (1609 loc) · 76.6 KB
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.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Apache.IoTDB.DataStructure;
using Microsoft.Extensions.Logging;
using Thrift;
using Thrift.Protocol;
using Thrift.Transport;
using Thrift.Transport.Client;
namespace Apache.IoTDB
{
public partial class SessionPool : IDisposable, IPoolDiagnosticReporter
{
private static readonly TSProtocolVersion ProtocolVersion = TSProtocolVersion.IOTDB_SERVICE_PROTOCOL_V3;
private const string DepletionReasonReconnectFailed = "Reconnection failed";
private readonly string _username;
private readonly string _password;
private bool _enableRpcCompression;
private string _zoneId;
private readonly List<string> _nodeUrls = new();
private readonly List<TEndPoint> _endPoints = new();
private readonly string _host;
private readonly int _port;
private readonly bool _useSsl;
private readonly string _certificatePath;
private readonly int _fetchSize;
/// <summary>
/// _timeout is the amount of time a Session will wait for a send operation to complete successfully.
/// </summary>
private readonly int _timeout;
private readonly int _poolSize = 4;
private readonly string _sqlDialect = IoTDBConstant.TREE_SQL_DIALECT;
private string _database;
private readonly Utils _utilFunctions = new();
private const int RetryNum = 3;
private bool _debugMode;
private bool _isClose = true;
private ConcurrentClientQueue _clients;
private ILogger _logger;
private PoolHealthMetrics _healthMetrics;
public delegate Task<TResult> AsyncOperation<TResult>(Client client);
/// <summary>
/// Retrieves current count of idle clients ready for operations.
/// </summary>
public int AvailableClients => _clients?.ClientQueue.Count ?? 0;
/// <summary>
/// Retrieves the configured maximum capacity of the session pool.
/// </summary>
public int TotalPoolSize => _healthMetrics?.GetConfiguredMaxSize() ?? _poolSize;
/// <summary>
/// Retrieves cumulative tally of reconnection failures since pool was opened.
/// </summary>
public int FailedReconnections => _healthMetrics?.GetReconnectionFailureTally() ?? 0;
[Obsolete("This method is deprecated, please use new SessionPool.Builder().")]
public SessionPool(string host, int port, int poolSize)
: this(host, port, "root", "root", 1024, "Asia/Shanghai", poolSize, true, 60)
{
}
[Obsolete(" This method is deprecated, please use new SessionPool.Builder().")]
public SessionPool(string host, int port, string username, string password)
: this(host, port, username, password, 1024, "Asia/Shanghai", 8, true, 60)
{
}
public SessionPool(string host, int port, string username, string password, int fetchSize)
: this(host, port, username, password, fetchSize, "Asia/Shanghai", 8, true, 60)
{
}
public SessionPool(string host, int port) : this(host, port, "root", "root", 1024, "Asia/Shanghai", 8, true, 60)
{
}
public SessionPool(string host, int port, string username, string password, int fetchSize, string zoneId, int poolSize, bool enableRpcCompression, int timeout)
: this(host, port, username, password, fetchSize, zoneId, poolSize, enableRpcCompression, timeout, false, null, IoTDBConstant.TREE_SQL_DIALECT, "")
{
}
protected internal SessionPool(string host, int port, string username, string password, int fetchSize, string zoneId, int poolSize, bool enableRpcCompression, int timeout, bool useSsl, string certificatePath, string sqlDialect, string database)
{
_host = host;
_port = port;
_username = username;
_password = password;
_zoneId = zoneId;
_fetchSize = fetchSize;
_debugMode = false;
_poolSize = poolSize;
_enableRpcCompression = enableRpcCompression;
_timeout = timeout;
_useSsl = useSsl;
_certificatePath = certificatePath;
_sqlDialect = sqlDialect;
_database = database;
}
/// <summary>
/// Initializes a new instance of the <see cref="SessionPool"/> class.
/// </summary>
/// <param name="nodeUrls">The list of node URLs to connect to, multiple ip:rpcPort eg.127.0.0.1:9001</param>
/// <param name="poolSize">The size of the session pool.</param>
public SessionPool(List<string> nodeUrls, int poolSize)
: this(nodeUrls, "root", "root", 1024, "Asia/Shanghai", poolSize, true, 60)
{
}
public SessionPool(List<string> nodeUrls, string username, string password)
: this(nodeUrls, username, password, 1024, "Asia/Shanghai", 8, true, 60)
{
}
public SessionPool(List<string> nodeUrls, string username, string password, int fetchSize)
: this(nodeUrls, username, password, fetchSize, "Asia/Shanghai", 8, true, 60)
{
}
public SessionPool(List<string> nodeUrls, string username, string password, int fetchSize, string zoneId)
: this(nodeUrls, username, password, fetchSize, zoneId, 8, true, 60)
{
}
public SessionPool(List<string> nodeUrls, string username, string password, int fetchSize, string zoneId, int poolSize, bool enableRpcCompression, int timeout)
: this(nodeUrls, username, password, fetchSize, zoneId, poolSize, enableRpcCompression, timeout, false, null, IoTDBConstant.TREE_SQL_DIALECT, "")
{
}
protected internal SessionPool(List<string> nodeUrls, string username, string password, int fetchSize, string zoneId, int poolSize, bool enableRpcCompression, int timeout, bool useSsl, string certificatePath, string sqlDialect, string database)
{
if (nodeUrls.Count == 0)
{
throw new ArgumentException("nodeUrls shouldn't be empty.");
}
_nodeUrls = nodeUrls;
_endPoints = _utilFunctions.ParseSeedNodeUrls(nodeUrls);
_username = username;
_password = password;
_zoneId = zoneId;
_fetchSize = fetchSize;
_debugMode = false;
_poolSize = poolSize;
_enableRpcCompression = enableRpcCompression;
_timeout = timeout;
_useSsl = useSsl;
_certificatePath = certificatePath;
_sqlDialect = sqlDialect;
_database = database;
}
public async Task<TResult> ExecuteClientOperationAsync<TResult>(AsyncOperation<TResult> operation, string errMsg, bool retryOnFailure = true, bool putClientBack = true)
{
Client client = _clients.Take();
bool shouldReturnClient = true;
bool operationSucceeded = false;
try
{
var resp = await operation(client);
operationSucceeded = true;
return resp;
}
catch (Exception ex)
{
if (retryOnFailure)
{
// Try to reconnect
try
{
client = await Reconnect(client);
// Reconnect succeeded, client is now a new healthy connection
}
catch (ReconnectionFailedException reconnectEx)
{
// Reconnection failed - original client was closed by Reconnect
shouldReturnClient = false;
throw new SessionPoolDepletedException(DepletionReasonReconnectFailed, AvailableClients, TotalPoolSize, FailedReconnections, reconnectEx);
}
// Reconnect succeeded, try the operation again
try
{
var resp = await operation(client);
operationSucceeded = true;
return resp;
}
catch (Exception retryEx)
{
// Retry operation failed, but client is healthy and should be returned to pool
// shouldReturnClient remains true
string detailedMsg = $"{errMsg}. {retryEx.Message}";
throw new TException(detailedMsg, retryEx);
}
}
else
{
// Preserve original error message from server
string detailedMsg = $"{errMsg}. {ex.Message}";
throw new TException(detailedMsg, ex);
}
}
finally
{
// Return client to pool if:
// 1. putClientBack is true (normal operations - client should always be returned), OR
// 2. putClientBack is false (query operations) BUT operation failed, meaning SessionDataSet
// wasn't created and won't manage the client
// Do NOT return if reconnection failed (shouldReturnClient is false) because client was closed by Reconnect
bool shouldReturnForQueryFailure = !putClientBack && !operationSucceeded;
if (shouldReturnClient && (putClientBack || shouldReturnForQueryFailure))
{
_clients.Add(client);
}
}
}
/// <summary>
/// Gets or sets the amount of time a Session will wait for a send operation to complete successfully.
/// </summary>
/// <remarks> The send time-out value, in milliseconds. The default is 10000.</remarks>
public int TimeOut { get; set; } = 10000;
ILoggerFactory factory;
private bool disposedValue;
public void OpenDebugMode(Action<ILoggingBuilder> configure)
{
_debugMode = true;
factory = LoggerFactory.Create(configure);
_logger = factory.CreateLogger(nameof(Apache.IoTDB));
}
public void CloseDebugMode()
{
_debugMode = false;
}
public async Task Open(bool enableRpcCompression, CancellationToken cancellationToken = default)
{
_enableRpcCompression = enableRpcCompression;
await Open(cancellationToken);
}
public async Task Open(CancellationToken cancellationToken = default)
{
_healthMetrics = new PoolHealthMetrics(_poolSize);
_clients = new ConcurrentClientQueue();
_clients.Timeout = _timeout * 5;
_clients.DiagnosticReporter = this;
if (_nodeUrls.Count == 0)
{
for (var index = 0; index < _poolSize; index++)
{
try
{
_clients.Add(await CreateAndOpen(_host, _port, _enableRpcCompression, _timeout, _useSsl, _certificatePath, _sqlDialect, _database, cancellationToken));
}
catch (Exception e)
{
_logger?.LogWarning(e, "Failed to create connection {0}/{1} to {2}:{3}", index + 1, _poolSize, _host, _port);
}
}
}
else
{
int startIndex = 0;
for (var index = 0; index < _poolSize; index++)
{
bool isConnected = false;
for (int i = 0; i < _endPoints.Count; i++)
{
var endPointIndex = (startIndex + i) % _endPoints.Count;
var endPoint = _endPoints[endPointIndex];
try
{
var client = await CreateAndOpen(endPoint.Ip, endPoint.Port, _enableRpcCompression, _timeout, _useSsl, _certificatePath, _sqlDialect, _database, cancellationToken);
_clients.Add(client);
isConnected = true;
startIndex = (endPointIndex + 1) % _endPoints.Count;
break;
}
catch (Exception e)
{
_logger?.LogWarning(e, "Failed to create connection to {0}:{1}", endPoint.Ip, endPoint.Port);
}
}
if (!isConnected) // current client could not connect to any endpoint
{
throw new TException("Error occurs when opening session pool. Could not connect to any server", null);
}
}
}
if (_clients.ClientQueue.Count != _poolSize)
{
throw new TException(string.Format("Error occurs when opening session pool. Client pool size is not equal to the expected size. Client pool size: {0}, expected size: {1}, Please check the server status", _clients.ClientQueue.Count, _poolSize), null);
}
_isClose = false;
}
public async Task<Client> Reconnect(Client originalClient = null, CancellationToken cancellationToken = default)
{
originalClient?.Transport.Close();
if (_nodeUrls.Count == 0)
{
for (int attempt = 1; attempt <= RetryNum; attempt++)
{
try
{
var client = await CreateAndOpen(_host, _port, _enableRpcCompression, _timeout, _useSsl, _certificatePath, _sqlDialect, _database, cancellationToken);
return client;
}
catch (Exception e)
{
_logger?.LogWarning(e, "Reconnection attempt {0}/{1} to {2}:{3} failed", attempt, RetryNum, _host, _port);
}
}
}
else
{
int startIndex = _endPoints.FindIndex(x => x.Ip == originalClient.EndPoint.Ip && x.Port == originalClient.EndPoint.Port);
if (startIndex == -1)
{
throw new ArgumentException($"The original client is not in the list of endpoints. Original client: {originalClient.EndPoint.Ip}:{originalClient.EndPoint.Port}");
}
for (int attempt = 1; attempt <= RetryNum; attempt++)
{
for (int i = 0; i < _endPoints.Count; i++)
{
int j = (startIndex + i) % _endPoints.Count;
try
{
var client = await CreateAndOpen(_endPoints[j].Ip, _endPoints[j].Port, _enableRpcCompression, _timeout, _useSsl, _certificatePath, _sqlDialect, _database, cancellationToken);
return client;
}
catch (Exception e)
{
_logger?.LogWarning(e, "Reconnection attempt {0}/{1} to {2}:{3} failed", attempt, RetryNum, _endPoints[j].Ip, _endPoints[j].Port);
}
}
}
}
_healthMetrics?.IncrementReconnectionFailures();
throw new ReconnectionFailedException("Error occurs when reconnecting session pool. Could not connect to any server");
}
public bool IsOpen() => !_isClose;
public async Task Close()
{
if (_isClose)
{
return;
}
foreach (var client in _clients.ClientQueue.AsEnumerable())
{
var closeSessionRequest = new TSCloseSessionReq(client.SessionId);
try
{
await client.ServiceClient.closeSessionAsync(closeSessionRequest);
}
catch (TException e)
{
throw new TException("Error occurs when closing session at server. Maybe server is down", e);
}
finally
{
_isClose = true;
client.Transport?.Close();
}
}
}
public async Task SetTimeZone(string zoneId)
{
_zoneId = zoneId;
foreach (var client in _clients.ClientQueue.AsEnumerable())
{
var req = new TSSetTimeZoneReq(client.SessionId, zoneId);
try
{
var resp = await client.ServiceClient.setTimeZoneAsync(req);
if (_debugMode)
{
_logger.LogInformation("setting time zone_id as {0}, server message:{1}", zoneId, resp.Message);
}
}
catch (TException e)
{
throw new TException("could not set time zone", e);
}
}
}
public async Task<string> GetTimeZone()
{
if (_zoneId != "")
{
return _zoneId;
}
var client = _clients.Take();
try
{
var response = await client.ServiceClient.getTimeZoneAsync(client.SessionId);
return response?.TimeZone;
}
catch (TException e)
{
throw new TException("could not get time zone", e);
}
finally
{
_clients.Add(client);
}
}
private async Task<Client> CreateAndOpen(string host, int port, bool enableRpcCompression, int timeout, bool useSsl, string cert, string sqlDialect, string database, CancellationToken cancellationToken = default)
{
TTransport socket = useSsl ?
new TTlsSocketTransport(host, port, null, timeout, new X509Certificate2(File.ReadAllBytes(cert))) :
new TSocketTransport(host, port, null, timeout);
var transport = new TFramedTransport(socket);
if (!transport.IsOpen)
{
await transport.OpenAsync(cancellationToken);
}
var client = enableRpcCompression ?
new IClientRPCService.Client(new TCompactProtocol(transport)) :
new IClientRPCService.Client(new TBinaryProtocol(transport));
var openReq = new TSOpenSessionReq(ProtocolVersion, _zoneId, _username)
{
Password = _password,
};
if (openReq.Configuration == null)
{
openReq.Configuration = new Dictionary<string, string>();
}
openReq.Configuration.Add("sql_dialect", sqlDialect);
if (!String.IsNullOrEmpty(database))
{
openReq.Configuration.Add("db", database);
}
try
{
var openResp = await client.openSessionAsync(openReq, cancellationToken);
if (openResp.ServerProtocolVersion != ProtocolVersion)
{
throw new TException($"Protocol Differ, Client version is {ProtocolVersion} but Server version is {openResp.ServerProtocolVersion}", null);
}
if (openResp.ServerProtocolVersion == 0)
{
throw new TException("Protocol not supported", null);
}
var sessionId = openResp.SessionId;
var statementId = await client.requestStatementIdAsync(sessionId, cancellationToken);
var endpoint = new TEndPoint(host, port);
var returnClient = new Client(
client,
sessionId,
statementId,
transport,
endpoint);
return returnClient;
}
catch (Exception)
{
transport.Close();
throw;
}
}
public async Task<int> CreateDatabase(string dbName)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var status = await client.ServiceClient.setStorageGroupAsync(client.SessionId, dbName);
if (_debugMode)
{
_logger.LogInformation("create database {0} successfully, server message is {1}", dbName, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when creating database"
);
}
[Obsolete("This method is deprecated, please use createDatabase instead.")]
public async Task<int> SetStorageGroup(string groupName)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var status = await client.ServiceClient.setStorageGroupAsync(client.SessionId, groupName);
if (_debugMode)
{
_logger.LogInformation("set storage group {0} successfully, server message is {1}", groupName, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when setting storage group"
);
}
public async Task<int> CreateTimeSeries(
string tsPath,
TSDataType dataType,
TSEncoding encoding,
Compressor compressor)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var req = new TSCreateTimeseriesReq(
client.SessionId,
tsPath,
(int)dataType,
(int)encoding,
(int)compressor);
var status = await client.ServiceClient.createTimeseriesAsync(req);
if (_debugMode)
{
_logger.LogInformation("creating time series {0} successfully, server message is {1}", tsPath, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when creating time series"
);
}
public async Task<int> CreateAlignedTimeseriesAsync(
string prefixPath,
List<string> measurements,
List<TSDataType> dataTypeLst,
List<TSEncoding> encodingLst,
List<Compressor> compressorLst)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var dataTypes = dataTypeLst.ConvertAll(x => (int)x);
var encodings = encodingLst.ConvertAll(x => (int)x);
var compressors = compressorLst.ConvertAll(x => (int)x);
var req = new TSCreateAlignedTimeseriesReq(
client.SessionId,
prefixPath,
measurements,
dataTypes,
encodings,
compressors);
var status = await client.ServiceClient.createAlignedTimeseriesAsync(req);
if (_debugMode)
{
_logger.LogInformation("creating aligned time series {0} successfully, server message is {1}", prefixPath, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when creating aligned time series"
);
}
public async Task<int> DeleteDatabaseAsync(string dbName)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var status = await client.ServiceClient.deleteStorageGroupsAsync(client.SessionId, new List<string> { dbName });
if (_debugMode)
{
_logger.LogInformation("delete database {0} successfully, server message is {1}", dbName, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when deleting database"
);
}
[Obsolete("This method is deprecated, please use DeleteDatabaseAsync instead.")]
public async Task<int> DeleteStorageGroupAsync(string groupName)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var status = await client.ServiceClient.deleteStorageGroupsAsync(client.SessionId, new List<string> { groupName });
if (_debugMode)
{
_logger.LogInformation("delete storage group {0} successfully, server message is {1}", groupName, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when deleting storage group"
);
}
public async Task<int> DeleteDatabasesAsync(List<string> dbNames)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var status = await client.ServiceClient.deleteStorageGroupsAsync(client.SessionId, dbNames);
if (_debugMode)
{
_logger.LogInformation("delete database(s) {0} successfully, server message is {1}", dbNames, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when deleting database(s)"
);
}
[Obsolete("This method is deprecated, please use DeleteDatabasesAsync instead.")]
public async Task<int> DeleteStorageGroupsAsync(List<string> groupNames)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var status = await client.ServiceClient.deleteStorageGroupsAsync(client.SessionId, groupNames);
if (_debugMode)
{
_logger.LogInformation("delete storage group(s) {0} successfully, server message is {1}", groupNames, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when deleting storage group(s)"
);
}
public async Task<int> CreateMultiTimeSeriesAsync(
List<string> tsPathLst,
List<TSDataType> dataTypeLst,
List<TSEncoding> encodingLst,
List<Compressor> compressorLst)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var dataTypes = dataTypeLst.ConvertAll(x => (int)x);
var encodings = encodingLst.ConvertAll(x => (int)x);
var compressors = compressorLst.ConvertAll(x => (int)x);
var req = new TSCreateMultiTimeseriesReq(client.SessionId, tsPathLst, dataTypes, encodings, compressors);
var status = await client.ServiceClient.createMultiTimeseriesAsync(req);
if (_debugMode)
{
_logger.LogInformation("creating multiple time series {0}, server message is {1}", tsPathLst, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when creating multiple time series"
);
}
public async Task<int> DeleteTimeSeriesAsync(List<string> pathList)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var status = await client.ServiceClient.deleteTimeseriesAsync(client.SessionId, pathList);
if (_debugMode)
{
_logger.LogInformation("deleting multiple time series {0}, server message is {1}", pathList, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when deleting multiple time series"
);
}
public async Task<int> DeleteTimeSeriesAsync(string tsPath)
{
return await DeleteTimeSeriesAsync(new List<string> { tsPath });
}
public async Task<bool> CheckTimeSeriesExistsAsync(string tsPath)
{
try
{
var sql = "SHOW TIMESERIES " + tsPath;
var sessionDataSet = await ExecuteQueryStatementAsync(sql);
bool timeSeriesExists = sessionDataSet.HasNext();
await sessionDataSet.Close(); // be sure to close the SessionDataSet to put the client back to the pool
return timeSeriesExists;
}
catch (TException e)
{
throw new TException("could not check if certain time series exists", e);
}
}
public async Task<int> DeleteDataAsync(List<string> tsPathLst, long startTime, long endTime)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var req = new TSDeleteDataReq(client.SessionId, tsPathLst, startTime, endTime);
var status = await client.ServiceClient.deleteDataAsync(req);
if (_debugMode)
{
_logger.LogInformation(
"delete data from {0}, server message is {1}",
tsPathLst,
status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when deleting data"
);
}
public async Task<int> InsertRecordAsync(string deviceId, RowRecord record)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var req = new TSInsertRecordReq(client.SessionId, deviceId, record.Measurements, record.ToBytes(), record.Timestamps);
var status = await client.ServiceClient.insertRecordAsync(req);
if (_debugMode)
{
_logger.LogInformation("insert one record to device {0}, server message: {1}", deviceId, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when inserting record"
);
}
public async Task<int> InsertAlignedRecordAsync(string deviceId, RowRecord record)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var req = new TSInsertRecordReq(client.SessionId, deviceId, record.Measurements, record.ToBytes(), record.Timestamps);
req.IsAligned = true;
// ASSERT that the insert plan is aligned
System.Diagnostics.Debug.Assert(req.IsAligned == true);
var status = await client.ServiceClient.insertRecordAsync(req);
if (_debugMode)
{
_logger.LogInformation("insert one record to device {0}, server message: {1}", deviceId, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when inserting record"
);
}
public TSInsertStringRecordReq GenInsertStrRecordReq(string deviceId, List<string> measurements,
List<string> values, long timestamp, long sessionId, bool isAligned = false)
{
if (values.Count() != measurements.Count())
{
throw new ArgumentException("length of data types does not equal to length of values!");
}
return new TSInsertStringRecordReq(sessionId, deviceId, measurements, values, timestamp)
{
IsAligned = isAligned
};
}
public TSInsertStringRecordsReq GenInsertStringRecordsReq(List<string> deviceIds, List<List<string>> measurementsList,
List<List<string>> valuesList, List<long> timestamps, long sessionId, bool isAligned = false)
{
if (valuesList.Count() != measurementsList.Count())
{
throw new ArgumentException("length of data types does not equal to length of values!");
}
return new TSInsertStringRecordsReq(sessionId, deviceIds, measurementsList, valuesList, timestamps)
{
IsAligned = isAligned
};
}
public TSInsertRecordsReq GenInsertRecordsReq(List<string> deviceId, List<RowRecord> rowRecords,
long sessionId)
{
var measurementLst = rowRecords.Select(x => x.Measurements).ToList();
var timestampLst = rowRecords.Select(x => x.Timestamps).ToList();
var valuesLstInBytes = rowRecords.Select(row => row.ToBytes()).ToList();
return new TSInsertRecordsReq(sessionId, deviceId, measurementLst, valuesLstInBytes, timestampLst);
}
public async Task<int> InsertStringRecordAsync(string deviceId, List<string> measurements, List<string> values,
long timestamp)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var req = GenInsertStrRecordReq(deviceId, measurements, values, timestamp, client.SessionId);
var status = await client.ServiceClient.insertStringRecordAsync(req);
if (_debugMode)
{
_logger.LogInformation("insert one string record to device {0}, server message: {1}", deviceId, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when inserting a string record"
);
}
public async Task<int> InsertAlignedStringRecordAsync(string deviceId, List<string> measurements, List<string> values,
long timestamp)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var req = GenInsertStrRecordReq(deviceId, measurements, values, timestamp, client.SessionId, true);
var status = await client.ServiceClient.insertStringRecordAsync(req);
if (_debugMode)
{
_logger.LogInformation("insert one record to device {0}, server message: {1}", deviceId, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when inserting a string record"
);
}
public async Task<int> InsertStringRecordsAsync(List<string> deviceIds, List<List<string>> measurements, List<List<string>> values,
List<long> timestamps)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var req = GenInsertStringRecordsReq(deviceIds, measurements, values, timestamps, client.SessionId);
var status = await client.ServiceClient.insertStringRecordsAsync(req);
if (_debugMode)
{
_logger.LogInformation("insert string records to devices {0}, server message: {1}", deviceIds, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when inserting string records"
);
}
public async Task<int> InsertAlignedStringRecordsAsync(List<string> deviceIds, List<List<string>> measurements, List<List<string>> values,
List<long> timestamps)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var req = GenInsertStringRecordsReq(deviceIds, measurements, values, timestamps, client.SessionId, true);
var status = await client.ServiceClient.insertStringRecordsAsync(req);
if (_debugMode)
{
_logger.LogInformation("insert string records to devices {0}, server message: {1}", deviceIds, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when inserting string records"
);
}
public async Task<int> InsertRecordsAsync(List<string> deviceId, List<RowRecord> rowRecords)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var req = GenInsertRecordsReq(deviceId, rowRecords, client.SessionId);
var status = await client.ServiceClient.insertRecordsAsync(req);
if (_debugMode)
{
_logger.LogInformation("insert multiple records to devices {0}, server message: {1}", deviceId, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when inserting records"
);
}
public async Task<int> InsertAlignedRecordsAsync(List<string> deviceId, List<RowRecord> rowRecords)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var req = GenInsertRecordsReq(deviceId, rowRecords, client.SessionId);
req.IsAligned = true;
// ASSERT that the insert plan is aligned
System.Diagnostics.Debug.Assert(req.IsAligned == true);
var status = await client.ServiceClient.insertRecordsAsync(req);
if (_debugMode)
{
_logger.LogInformation("insert multiple records to devices {0}, server message: {1}", deviceId, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when inserting records"
);
}
public TSInsertTabletReq GenInsertTabletReq(Tablet tablet, long sessionId)
{
return new TSInsertTabletReq(
sessionId,
tablet.InsertTargetName,
tablet.Measurements,
tablet.GetBinaryValues(),
tablet.GetBinaryTimestamps(),
tablet.GetDataTypes(),
tablet.RowNumber);
}
public async Task<int> InsertTabletAsync(Tablet tablet)
{
return await ExecuteClientOperationAsync<int>(
async client =>
{
var req = GenInsertTabletReq(tablet, client.SessionId);
var status = await client.ServiceClient.insertTabletAsync(req);
if (_debugMode)
{
_logger.LogInformation("insert one tablet to device {0}, server message: {1}", tablet.InsertTargetName, status.Message);
}
return _utilFunctions.VerifySuccess(status);
},
errMsg: "Error occurs when inserting tablet"
);
}
public async Task<int> InsertAlignedTabletAsync(Tablet tablet)