iginx-pyclient 0.6.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- iginx_pyclient/__init__.py +17 -0
- iginx_pyclient/cluster_info.py +53 -0
- iginx_pyclient/dataset.py +266 -0
- iginx_pyclient/session.py +739 -0
- iginx_pyclient/thrift/__init__.py +0 -0
- iginx_pyclient/thrift/rpc/IService.py +6863 -0
- iginx_pyclient/thrift/rpc/__init__.py +1 -0
- iginx_pyclient/thrift/rpc/constants.py +14 -0
- iginx_pyclient/thrift/rpc/ttypes.py +8961 -0
- iginx_pyclient/time_series.py +36 -0
- iginx_pyclient/utils/__init__.py +17 -0
- iginx_pyclient/utils/bitmap.py +41 -0
- iginx_pyclient/utils/byte_utils.py +212 -0
- iginx_pyclient-0.6.0.dist-info/LICENSE +201 -0
- iginx_pyclient-0.6.0.dist-info/METADATA +38 -0
- iginx_pyclient-0.6.0.dist-info/RECORD +26 -0
- iginx_pyclient-0.6.0.dist-info/WHEEL +5 -0
- iginx_pyclient-0.6.0.dist-info/top_level.txt +1 -0
- thrift/__init__.py +0 -0
- thrift/rpc/IService.py +6863 -0
- thrift/rpc/__init__.py +1 -0
- thrift/rpc/constants.py +14 -0
- thrift/rpc/ttypes.py +8961 -0
- utils/__init__.py +17 -0
- utils/bitmap.py +41 -0
- utils/byte_utils.py +212 -0
|
@@ -0,0 +1,739 @@
|
|
|
1
|
+
# Licensed to the Apache Software Foundation (ASF) under one
|
|
2
|
+
# or more contributor license agreements. See the NOTICE file
|
|
3
|
+
# distributed with this work for additional information
|
|
4
|
+
# regarding copyright ownership. The ASF licenses this file
|
|
5
|
+
# to you under the Apache License, Version 2.0 (the
|
|
6
|
+
# "License"); you may not use this file except in compliance
|
|
7
|
+
# with the License. You may obtain a copy of the License at
|
|
8
|
+
#
|
|
9
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
#
|
|
11
|
+
# Unless required by applicable law or agreed to in writing,
|
|
12
|
+
# software distributed under the License is distributed on an
|
|
13
|
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
14
|
+
# KIND, either express or implied. See the License for the
|
|
15
|
+
# specific language governing permissions and limitations
|
|
16
|
+
# under the License.
|
|
17
|
+
#
|
|
18
|
+
import csv
|
|
19
|
+
import logging
|
|
20
|
+
import os.path
|
|
21
|
+
from datetime import datetime
|
|
22
|
+
|
|
23
|
+
from thrift.protocol import TBinaryProtocol
|
|
24
|
+
from thrift.transport import TSocket, TTransport
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
from .cluster_info import ClusterInfo
|
|
28
|
+
from .dataset import QueryDataSet, AggregateQueryDataSet, StatementExecuteDataSet
|
|
29
|
+
from .thrift.rpc.IService import Client
|
|
30
|
+
from .thrift.rpc.ttypes import (
|
|
31
|
+
OpenSessionReq,
|
|
32
|
+
CloseSessionReq,
|
|
33
|
+
AddUserReq,
|
|
34
|
+
UpdateUserReq,
|
|
35
|
+
DeleteUserReq,
|
|
36
|
+
GetClusterInfoReq,
|
|
37
|
+
GetReplicaNumReq,
|
|
38
|
+
LastQueryReq,
|
|
39
|
+
ShowColumnsReq,
|
|
40
|
+
AddStorageEnginesReq,
|
|
41
|
+
DeleteColumnsReq,
|
|
42
|
+
QueryDataReq,
|
|
43
|
+
DeleteDataInColumnsReq,
|
|
44
|
+
DownsampleQueryReq,
|
|
45
|
+
AggregateQueryReq,
|
|
46
|
+
InsertRowRecordsReq,
|
|
47
|
+
InsertNonAlignedRowRecordsReq,
|
|
48
|
+
InsertColumnRecordsReq,
|
|
49
|
+
InsertNonAlignedColumnRecordsReq,
|
|
50
|
+
ExecuteSqlReq,
|
|
51
|
+
ExecuteStatementReq,
|
|
52
|
+
FetchResultsReq,
|
|
53
|
+
CloseStatementReq,
|
|
54
|
+
DebugInfoReq,
|
|
55
|
+
LoadCSVReq,
|
|
56
|
+
|
|
57
|
+
StorageEngine, DataType,
|
|
58
|
+
)
|
|
59
|
+
from .time_series import TimeSeries
|
|
60
|
+
from .utils.bitmap import Bitmap
|
|
61
|
+
from .utils.byte_utils import timestamps_to_bytes, row_values_to_bytes, column_values_to_bytes, bitmap_to_bytes
|
|
62
|
+
|
|
63
|
+
logger = logging.getLogger("IginX")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Session(object):
|
|
67
|
+
SUCCESS_CODE = 200
|
|
68
|
+
DEFAULT_USER = "root"
|
|
69
|
+
DEFAULT_PASSWORD = "root"
|
|
70
|
+
|
|
71
|
+
def __init__(self, host, port, user=DEFAULT_USER, password=DEFAULT_PASSWORD):
|
|
72
|
+
self.__host = host
|
|
73
|
+
self.__port = port
|
|
74
|
+
self.__user = user
|
|
75
|
+
self.__password = password
|
|
76
|
+
|
|
77
|
+
self.__is_close = True
|
|
78
|
+
self.__transport = None
|
|
79
|
+
self.__client = None
|
|
80
|
+
self.__session_id = None
|
|
81
|
+
|
|
82
|
+
def open(self):
|
|
83
|
+
if not self.__is_close:
|
|
84
|
+
return
|
|
85
|
+
|
|
86
|
+
self.__transport = TSocket.TSocket(self.__host, self.__port)
|
|
87
|
+
|
|
88
|
+
if not self.__transport.isOpen():
|
|
89
|
+
try:
|
|
90
|
+
self.__transport.open()
|
|
91
|
+
except TTransport.TTransportException as e:
|
|
92
|
+
logger.exception("TTransportException!", exc_info=e)
|
|
93
|
+
|
|
94
|
+
self.__client = Client(TBinaryProtocol.TBinaryProtocol(self.__transport))
|
|
95
|
+
|
|
96
|
+
req = OpenSessionReq(self.__user, self.__password)
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
resp = self.__client.openSession(req)
|
|
100
|
+
Session.verify_status(resp.status)
|
|
101
|
+
self.__session_id = resp.sessionId
|
|
102
|
+
self.__is_close = False
|
|
103
|
+
except Exception as e:
|
|
104
|
+
self.__transport.close()
|
|
105
|
+
logger.exception("session closed because: ", exc_info=e)
|
|
106
|
+
|
|
107
|
+
def close(self):
|
|
108
|
+
if self.__is_close:
|
|
109
|
+
return
|
|
110
|
+
|
|
111
|
+
req = CloseSessionReq(self.__session_id)
|
|
112
|
+
try:
|
|
113
|
+
self.__client.closeSession(req)
|
|
114
|
+
except TTransport.TException as e:
|
|
115
|
+
logger.exception(
|
|
116
|
+
"Error occurs when closing session. Error message: ",
|
|
117
|
+
exc_info=e,
|
|
118
|
+
)
|
|
119
|
+
finally:
|
|
120
|
+
self.__is_close = True
|
|
121
|
+
if self.__transport is not None:
|
|
122
|
+
self.__transport.close()
|
|
123
|
+
|
|
124
|
+
def list_time_series(self):
|
|
125
|
+
req = ShowColumnsReq(sessionId=self.__session_id)
|
|
126
|
+
resp = self.__client.showColumns(req)
|
|
127
|
+
Session.verify_status(resp.status)
|
|
128
|
+
|
|
129
|
+
time_series_list = []
|
|
130
|
+
for i in range(len(resp.paths)):
|
|
131
|
+
time_series_list.append(TimeSeries(resp.paths[i], resp.dataTypeList[i]))
|
|
132
|
+
|
|
133
|
+
return time_series_list
|
|
134
|
+
|
|
135
|
+
def add_storage_engine(self, ip, port, type, extra_params=None):
|
|
136
|
+
self.batch_add_storage_engine([StorageEngine(ip, port, type, extraParams=extra_params)])
|
|
137
|
+
|
|
138
|
+
def batch_add_storage_engine(self, storage_engines):
|
|
139
|
+
req = AddStorageEnginesReq(sessionId=self.__session_id, storageEngines=storage_engines)
|
|
140
|
+
status = self.__client.addStorageEngines(req)
|
|
141
|
+
Session.verify_status(status)
|
|
142
|
+
|
|
143
|
+
def delete_time_series(self, path):
|
|
144
|
+
self.batch_delete_time_series([path])
|
|
145
|
+
|
|
146
|
+
def batch_delete_time_series(self, paths):
|
|
147
|
+
req = DeleteColumnsReq(sessionId=self.__session_id, paths=paths)
|
|
148
|
+
status = self.__client.deleteColumns(req)
|
|
149
|
+
Session.verify_status(status)
|
|
150
|
+
|
|
151
|
+
def get_replica_num(self):
|
|
152
|
+
req = GetReplicaNumReq(sessionId=self.__session_id)
|
|
153
|
+
resp = self.__client.getReplicaNum(req)
|
|
154
|
+
Session.verify_status(resp.status)
|
|
155
|
+
return resp.replicaNum
|
|
156
|
+
|
|
157
|
+
def insert_row_records(self, paths, timestamps, values_list, data_type_list, tags_list=None, timePrecision=None):
|
|
158
|
+
if len(paths) == 0 or len(timestamps) == 0 or len(values_list) == 0 or len(data_type_list) == 0:
|
|
159
|
+
raise RuntimeError("invalid insert request")
|
|
160
|
+
if len(paths) != len(data_type_list):
|
|
161
|
+
raise RuntimeError("the sizes of paths and data_type_list should be equal")
|
|
162
|
+
if len(timestamps) != len(values_list):
|
|
163
|
+
raise RuntimeError("the sizes of timestamps and values_list should be equal")
|
|
164
|
+
if tags_list is not None and len(tags_list) != len(paths):
|
|
165
|
+
raise RuntimeError("the sizes of paths, values_list, tags_list and data_type_list should be equal")
|
|
166
|
+
if timePrecision is not None and len(timePrecision) == 0:
|
|
167
|
+
raise RuntimeError("invalid timePrecision")
|
|
168
|
+
|
|
169
|
+
# 保证时间戳递增
|
|
170
|
+
index = [x for x in range(len(timestamps))]
|
|
171
|
+
index = sorted(index, key=lambda x: timestamps[x])
|
|
172
|
+
timestamps = sorted(timestamps)
|
|
173
|
+
sorted_values_list = []
|
|
174
|
+
for i in range(len(values_list)):
|
|
175
|
+
sorted_values_list.append(values_list[index[i]])
|
|
176
|
+
|
|
177
|
+
# 保证序列递增
|
|
178
|
+
index = [x for x in range(len(paths))]
|
|
179
|
+
index = sorted(index, key=lambda x: paths[x])
|
|
180
|
+
paths = sorted(paths)
|
|
181
|
+
# 重排数据类型
|
|
182
|
+
sorted_data_type_list = []
|
|
183
|
+
sorted_tags_list = []
|
|
184
|
+
for i in index:
|
|
185
|
+
sorted_data_type_list.append(data_type_list[i])
|
|
186
|
+
|
|
187
|
+
if tags_list is not None:
|
|
188
|
+
for i in index:
|
|
189
|
+
sorted_tags_list.append(tags_list[i])
|
|
190
|
+
|
|
191
|
+
# 重排数据
|
|
192
|
+
for i in range(len(sorted_values_list)):
|
|
193
|
+
values = []
|
|
194
|
+
for j in range(len(paths)):
|
|
195
|
+
values.append(sorted_values_list[i][index[j]])
|
|
196
|
+
sorted_values_list[i] = values
|
|
197
|
+
|
|
198
|
+
values_buffer_list = []
|
|
199
|
+
bitmap_buffer_list = []
|
|
200
|
+
for i in range(len(timestamps)):
|
|
201
|
+
values = sorted_values_list[i]
|
|
202
|
+
values_buffer_list.append(row_values_to_bytes(values, sorted_data_type_list))
|
|
203
|
+
bitmap = Bitmap(len(values))
|
|
204
|
+
for j in range(len(values)):
|
|
205
|
+
if values[j] is not None:
|
|
206
|
+
bitmap.set(j)
|
|
207
|
+
bitmap_buffer_list.append(bitmap_to_bytes(bitmap.get_bytes()))
|
|
208
|
+
|
|
209
|
+
req = InsertRowRecordsReq(sessionId=self.__session_id, paths=paths, keys=timestamps_to_bytes(timestamps),
|
|
210
|
+
valuesList=values_buffer_list,
|
|
211
|
+
bitmapList=bitmap_buffer_list, dataTypeList=sorted_data_type_list,
|
|
212
|
+
tagsList=sorted_tags_list, timePrecision=timePrecision)
|
|
213
|
+
status = self.__client.insertRowRecords(req)
|
|
214
|
+
Session.verify_status(status)
|
|
215
|
+
|
|
216
|
+
def insert_non_aligned_row_records(self, paths, timestamps, values_list, data_type_list, tags_list=None,
|
|
217
|
+
timePrecision=None):
|
|
218
|
+
if len(paths) == 0 or len(timestamps) == 0 or len(values_list) == 0 or len(data_type_list) == 0:
|
|
219
|
+
raise RuntimeError("invalid insert request")
|
|
220
|
+
if len(paths) != len(data_type_list):
|
|
221
|
+
raise RuntimeError("the sizes of paths and data_type_list should be equal")
|
|
222
|
+
if len(timestamps) != len(values_list):
|
|
223
|
+
raise RuntimeError("the sizes of timestamps and values_list should be equal")
|
|
224
|
+
if tags_list is not None and len(tags_list) != len(paths):
|
|
225
|
+
raise RuntimeError("the sizes of paths, values_list, tags_list and data_type_list should be equal")
|
|
226
|
+
if timePrecision is not None and len(timePrecision) == 0:
|
|
227
|
+
raise RuntimeError("invalid timePrecision")
|
|
228
|
+
|
|
229
|
+
# 保证时间戳递增
|
|
230
|
+
index = [x for x in range(len(timestamps))]
|
|
231
|
+
index = sorted(index, key=lambda x: timestamps[x])
|
|
232
|
+
timestamps = sorted(timestamps)
|
|
233
|
+
sorted_values_list = []
|
|
234
|
+
for i in range(len(values_list)):
|
|
235
|
+
sorted_values_list.append(values_list[index[i]])
|
|
236
|
+
|
|
237
|
+
# 保证序列递增
|
|
238
|
+
index = [x for x in range(len(paths))]
|
|
239
|
+
index = sorted(index, key=lambda x: paths[x])
|
|
240
|
+
paths = sorted(paths)
|
|
241
|
+
# 重排数据类型
|
|
242
|
+
sorted_data_type_list = []
|
|
243
|
+
sorted_tags_list = []
|
|
244
|
+
for i in index:
|
|
245
|
+
sorted_data_type_list.append(data_type_list[i])
|
|
246
|
+
|
|
247
|
+
if tags_list is not None:
|
|
248
|
+
for i in index:
|
|
249
|
+
sorted_tags_list.append(tags_list[i])
|
|
250
|
+
|
|
251
|
+
# 重排数据
|
|
252
|
+
for i in range(len(sorted_values_list)):
|
|
253
|
+
values = []
|
|
254
|
+
for j in range(len(paths)):
|
|
255
|
+
values.append(sorted_values_list[i][index[j]])
|
|
256
|
+
sorted_values_list[i] = values
|
|
257
|
+
|
|
258
|
+
values_buffer_list = []
|
|
259
|
+
bitmap_buffer_list = []
|
|
260
|
+
for i in range(len(timestamps)):
|
|
261
|
+
values = sorted_values_list[i]
|
|
262
|
+
values_buffer_list.append(row_values_to_bytes(values, sorted_data_type_list))
|
|
263
|
+
bitmap = Bitmap(len(values))
|
|
264
|
+
for j in range(len(values)):
|
|
265
|
+
if values[j] is not None:
|
|
266
|
+
bitmap.set(j)
|
|
267
|
+
bitmap_buffer_list.append(bitmap_to_bytes(bitmap.get_bytes()))
|
|
268
|
+
|
|
269
|
+
req = InsertNonAlignedRowRecordsReq(sessionId=self.__session_id, paths=paths,
|
|
270
|
+
timestamps=timestamps_to_bytes(timestamps), valuesList=values_buffer_list,
|
|
271
|
+
bitmapList=bitmap_buffer_list, dataTypeList=sorted_data_type_list,
|
|
272
|
+
tagsList=sorted_tags_list, timePrecision=timePrecision)
|
|
273
|
+
status = self.__client.insertNonAlignedRowRecords(req)
|
|
274
|
+
Session.verify_status(status)
|
|
275
|
+
|
|
276
|
+
def insert_column_records(self, paths, timestamps, values_list, data_type_list, tags_list=None, timePrecision=None):
|
|
277
|
+
if len(paths) == 0 or len(timestamps) == 0 or len(values_list) == 0 or len(data_type_list) == 0:
|
|
278
|
+
raise RuntimeError("invalid insert request")
|
|
279
|
+
if len(paths) != len(data_type_list):
|
|
280
|
+
raise RuntimeError("the sizes of paths and data_type_list should be equal")
|
|
281
|
+
if len(paths) != len(values_list):
|
|
282
|
+
raise RuntimeError("the sizes of paths and values_list should be equal")
|
|
283
|
+
if tags_list is not None and len(paths) != len(tags_list):
|
|
284
|
+
raise RuntimeError("the sizes of paths, valuesList, dataTypeList and tagsList should be equal")
|
|
285
|
+
if timePrecision is not None and len(timePrecision) == 0:
|
|
286
|
+
raise RuntimeError("invalid timePrecision")
|
|
287
|
+
|
|
288
|
+
# 保证时间戳递增
|
|
289
|
+
index = [x for x in range(len(timestamps))]
|
|
290
|
+
index = sorted(index, key=lambda x: timestamps[x])
|
|
291
|
+
timestamps = sorted(timestamps)
|
|
292
|
+
for i in range(len(values_list)):
|
|
293
|
+
values = []
|
|
294
|
+
for j in range(len(timestamps)):
|
|
295
|
+
values.append(values_list[i][index[j]])
|
|
296
|
+
values_list[i] = values
|
|
297
|
+
|
|
298
|
+
# 保证序列递增
|
|
299
|
+
index = [x for x in range(len(paths))]
|
|
300
|
+
index = sorted(index, key=lambda x: paths[x])
|
|
301
|
+
paths = sorted(paths)
|
|
302
|
+
# 重排数据类型
|
|
303
|
+
sorted_values_list = []
|
|
304
|
+
sorted_data_type_list = []
|
|
305
|
+
sorted_tags_list = []
|
|
306
|
+
for i in index:
|
|
307
|
+
sorted_values_list.append(values_list[index[i]])
|
|
308
|
+
sorted_data_type_list.append(data_type_list[index[i]])
|
|
309
|
+
if tags_list is not None:
|
|
310
|
+
for i in index:
|
|
311
|
+
sorted_tags_list.append(tags_list[i])
|
|
312
|
+
|
|
313
|
+
values_buffer_list = []
|
|
314
|
+
bitmap_buffer_list = []
|
|
315
|
+
for i in range(len(paths)):
|
|
316
|
+
values = sorted_values_list[i]
|
|
317
|
+
values_buffer_list.append(column_values_to_bytes(values, sorted_data_type_list[i]))
|
|
318
|
+
bitmap = Bitmap(len(timestamps))
|
|
319
|
+
for j in range(len(timestamps)):
|
|
320
|
+
if values[j] is not None:
|
|
321
|
+
bitmap.set(j)
|
|
322
|
+
bitmap_buffer_list.append(bitmap_to_bytes(bitmap.get_bytes()))
|
|
323
|
+
|
|
324
|
+
req = InsertColumnRecordsReq(sessionId=self.__session_id, paths=paths,
|
|
325
|
+
timestamps=timestamps_to_bytes(timestamps),
|
|
326
|
+
valuesList=values_buffer_list,
|
|
327
|
+
bitmapList=bitmap_buffer_list, dataTypeList=sorted_data_type_list,
|
|
328
|
+
tagsList=sorted_tags_list, timePrecision=timePrecision)
|
|
329
|
+
status = self.__client.insertColumnRecords(req)
|
|
330
|
+
Session.verify_status(status)
|
|
331
|
+
|
|
332
|
+
def insert_non_aligned_column_records(self, paths, timestamps, values_list, data_type_list, tags_list=None,
|
|
333
|
+
timePrecision=None):
|
|
334
|
+
if len(paths) == 0 or len(timestamps) == 0 or len(values_list) == 0 or len(data_type_list) == 0:
|
|
335
|
+
raise RuntimeError("invalid insert request")
|
|
336
|
+
if len(paths) != len(data_type_list):
|
|
337
|
+
raise RuntimeError("the sizes of paths and data_type_list should be equal")
|
|
338
|
+
if len(paths) != len(values_list):
|
|
339
|
+
raise RuntimeError("the sizes of paths and values_list should be equal")
|
|
340
|
+
if tags_list is not None and len(paths) != len(tags_list):
|
|
341
|
+
raise RuntimeError("the sizes of paths, valuesList, dataTypeList and tagsList should be equal")
|
|
342
|
+
if timePrecision is not None and len(timePrecision) == 0:
|
|
343
|
+
raise RuntimeError("invalid timePrecision")
|
|
344
|
+
|
|
345
|
+
# 保证时间戳递增
|
|
346
|
+
index = [x for x in range(len(timestamps))]
|
|
347
|
+
index = sorted(index, key=lambda x: timestamps[x])
|
|
348
|
+
timestamps = sorted(timestamps)
|
|
349
|
+
for i in range(len(values_list)):
|
|
350
|
+
values = []
|
|
351
|
+
for j in range(len(timestamps)):
|
|
352
|
+
values.append(values_list[i][index[j]])
|
|
353
|
+
values_list[i] = values
|
|
354
|
+
|
|
355
|
+
# 保证序列递增
|
|
356
|
+
index = [x for x in range(len(paths))]
|
|
357
|
+
index = sorted(index, key=lambda x: paths[x])
|
|
358
|
+
paths = sorted(paths)
|
|
359
|
+
# 重排数据类型
|
|
360
|
+
sorted_values_list = []
|
|
361
|
+
sorted_data_type_list = []
|
|
362
|
+
sorted_tags_list = []
|
|
363
|
+
for i in index:
|
|
364
|
+
sorted_values_list.append(values_list[index[i]])
|
|
365
|
+
sorted_data_type_list.append(data_type_list[index[i]])
|
|
366
|
+
if tags_list is not None:
|
|
367
|
+
for i in index:
|
|
368
|
+
sorted_tags_list.append(tags_list[i])
|
|
369
|
+
|
|
370
|
+
values_buffer_list = []
|
|
371
|
+
bitmap_buffer_list = []
|
|
372
|
+
for i in range(len(paths)):
|
|
373
|
+
values = sorted_values_list[i]
|
|
374
|
+
values_buffer_list.append(column_values_to_bytes(values, sorted_data_type_list[i]))
|
|
375
|
+
bitmap = Bitmap(len(timestamps))
|
|
376
|
+
for j in range(len(timestamps)):
|
|
377
|
+
if values[j] is not None:
|
|
378
|
+
bitmap.set(j)
|
|
379
|
+
bitmap_buffer_list.append(bitmap_to_bytes(bitmap.get_bytes()))
|
|
380
|
+
|
|
381
|
+
req = InsertNonAlignedColumnRecordsReq(sessionId=self.__session_id, paths=paths,
|
|
382
|
+
timestamps=timestamps_to_bytes(timestamps),
|
|
383
|
+
valuesList=values_buffer_list,
|
|
384
|
+
bitmapList=bitmap_buffer_list, dataTypeList=sorted_data_type_list,
|
|
385
|
+
tagsList=sorted_tags_list, timePrecision=timePrecision)
|
|
386
|
+
status = self.__client.insertNonAlignedColumnRecords(req)
|
|
387
|
+
Session.verify_status(status)
|
|
388
|
+
|
|
389
|
+
def query(self, paths, start_time, end_time, timePrecision=None):
|
|
390
|
+
req = QueryDataReq(sessionId=self.__session_id, paths=Session.merge_and_sort_paths(paths),
|
|
391
|
+
startKey=start_time, endKey=end_time, timePrecision=timePrecision)
|
|
392
|
+
resp = self.__client.queryData(req)
|
|
393
|
+
Session.verify_status(resp.status)
|
|
394
|
+
paths = resp.paths
|
|
395
|
+
data_types = resp.dataTypeList
|
|
396
|
+
raw_data_set = resp.queryDataSet
|
|
397
|
+
return QueryDataSet(paths, data_types, raw_data_set.keys, raw_data_set.valuesList, raw_data_set.bitmapList)
|
|
398
|
+
|
|
399
|
+
def last_query(self, paths, start_time=0, timePrecision=None):
|
|
400
|
+
if len(paths) == 0:
|
|
401
|
+
logger.warning("paths shouldn't be empty")
|
|
402
|
+
return None
|
|
403
|
+
req = LastQueryReq(sessionId=self.__session_id, paths=Session.merge_and_sort_paths(paths), startKey=start_time,
|
|
404
|
+
timePrecision=timePrecision)
|
|
405
|
+
resp = self.__client.lastQuery(req)
|
|
406
|
+
Session.verify_status(resp.status)
|
|
407
|
+
paths = resp.paths
|
|
408
|
+
data_types = resp.dataTypeList
|
|
409
|
+
raw_data_set = resp.queryDataSet
|
|
410
|
+
return QueryDataSet(paths, data_types, raw_data_set.keys, raw_data_set.valuesList,
|
|
411
|
+
raw_data_set.bitmapList)
|
|
412
|
+
|
|
413
|
+
def downsample_query(self, paths, start_time, end_time, type, precision, timePrecision=None):
|
|
414
|
+
req = DownsampleQueryReq(sessionId=self.__session_id, paths=paths, startTime=start_time, endTime=end_time,
|
|
415
|
+
aggregateType=type,
|
|
416
|
+
precision=precision, timePrecision=timePrecision)
|
|
417
|
+
resp = self.__client.downsampleQuery(req)
|
|
418
|
+
Session.verify_status(resp.status)
|
|
419
|
+
paths = resp.paths
|
|
420
|
+
data_types = resp.dataTypeList
|
|
421
|
+
raw_data_set = resp.queryDataSet
|
|
422
|
+
return QueryDataSet(paths, data_types, raw_data_set.keys, raw_data_set.valuesList,
|
|
423
|
+
raw_data_set.bitmapList)
|
|
424
|
+
|
|
425
|
+
def aggregate_query(self, paths, start_time, end_time, type, timePrecision=None):
|
|
426
|
+
req = AggregateQueryReq(sessionId=self.__session_id, paths=paths, startKey=start_time, endKey=end_time,
|
|
427
|
+
aggregateType=type, timePrecision=timePrecision)
|
|
428
|
+
resp = self.__client.aggregateQuery(req)
|
|
429
|
+
Session.verify_status(resp.status)
|
|
430
|
+
return AggregateQueryDataSet(resp=resp, type=type)
|
|
431
|
+
|
|
432
|
+
def delete_data(self, path, start_time, end_time, timePrecision=None):
|
|
433
|
+
self.batch_delete_data([path], start_time, end_time, timePrecision)
|
|
434
|
+
|
|
435
|
+
def batch_delete_data(self, paths, start_time, end_time, timePrecision=None):
|
|
436
|
+
req = DeleteDataInColumnsReq(sessionId=self.__session_id, paths=paths, startTime=start_time, endTime=end_time,
|
|
437
|
+
timePrecision=timePrecision)
|
|
438
|
+
status = self.__client.deleteDataInColumns(req)
|
|
439
|
+
Session.verify_status(status)
|
|
440
|
+
|
|
441
|
+
def add_user(self, username, password, auths):
|
|
442
|
+
req = AddUserReq(sessionId=self.__session_id, username=username, password=password, auths=auths)
|
|
443
|
+
status = self.__client.addUser(req)
|
|
444
|
+
Session.verify_status(status)
|
|
445
|
+
|
|
446
|
+
def delete_user(self, username):
|
|
447
|
+
req = DeleteUserReq(sessionId=self.__session_id, username=username)
|
|
448
|
+
status = self.__client.deleteUser(req)
|
|
449
|
+
Session.verify_status(status)
|
|
450
|
+
|
|
451
|
+
def update_user(self, username, password=None, auths=None):
|
|
452
|
+
req = UpdateUserReq(sessionId=self.__session_id, username=username)
|
|
453
|
+
if password:
|
|
454
|
+
req.password = password
|
|
455
|
+
if auths:
|
|
456
|
+
req.auths = auths
|
|
457
|
+
status = self.__client.updateUser(req)
|
|
458
|
+
Session.verify_status(status)
|
|
459
|
+
|
|
460
|
+
def get_cluster_info(self):
|
|
461
|
+
req = GetClusterInfoReq(sessionId=self.__session_id)
|
|
462
|
+
resp = self.__client.getClusterInfo(req)
|
|
463
|
+
Session.verify_status(resp.status)
|
|
464
|
+
return ClusterInfo(resp)
|
|
465
|
+
|
|
466
|
+
def execute_sql(self, statement):
|
|
467
|
+
req = ExecuteSqlReq(sessionId=self.__session_id, statement=statement)
|
|
468
|
+
resp = self.__client.executeSql(req)
|
|
469
|
+
Session.verify_status(resp.status)
|
|
470
|
+
return resp
|
|
471
|
+
|
|
472
|
+
def execute_statement(self, statement, fetch_size=2147483647):
|
|
473
|
+
req = ExecuteStatementReq(sessionId=self.__session_id, statement=statement, fetchSize=fetch_size)
|
|
474
|
+
resp = self.__client.executeStatement(req)
|
|
475
|
+
Session.verify_status(resp.status)
|
|
476
|
+
return StatementExecuteDataSet(self, resp.queryId, resp.columns, resp.dataTypeList, fetch_size,
|
|
477
|
+
resp.queryDataSet.valuesList, resp.queryDataSet.bitmapList, resp.exportStreamDir,
|
|
478
|
+
resp.exportCSV)
|
|
479
|
+
|
|
480
|
+
def load_csv(self, statement):
|
|
481
|
+
req = ExecuteSqlReq(sessionId=self.__session_id, statement=statement)
|
|
482
|
+
resp = self.__client.executeSql(req)
|
|
483
|
+
Session.verify_status(resp.status)
|
|
484
|
+
|
|
485
|
+
path = resp.loadCsvPath
|
|
486
|
+
file = Path(path)
|
|
487
|
+
if not file.is_file():
|
|
488
|
+
raise ValueError(f"{path} is not a file!")
|
|
489
|
+
if not path.endswith(".csv"):
|
|
490
|
+
raise ValueError(f"The file name must end with [.csv], {path} doesn't satisfy the requirement!")
|
|
491
|
+
|
|
492
|
+
with open(file, 'rb') as f:
|
|
493
|
+
bytes_content = f.read() # 读取文件内容为bytes
|
|
494
|
+
|
|
495
|
+
csv_content = bytes_content
|
|
496
|
+
req = LoadCSVReq(sessionId=self.__session_id, statement=statement, csvFile=csv_content)
|
|
497
|
+
resp = self.__client.loadCSV(req)
|
|
498
|
+
Session.verify_status(resp.status)
|
|
499
|
+
return resp
|
|
500
|
+
|
|
501
|
+
# load all files in a directory into IGinX database
|
|
502
|
+
def load_directory(self, dir_path, chunk_size=1024 * 10):
|
|
503
|
+
all_files = [os.path.join(dir_path, f) for f in os.listdir(dir_path) if
|
|
504
|
+
os.path.isfile(os.path.join(dir_path, f))]
|
|
505
|
+
for file_path in all_files:
|
|
506
|
+
print(f"Reading file: {file_path}")
|
|
507
|
+
self.load_file_by_chunks(file_path, chunk_size)
|
|
508
|
+
print(f"Load file: {file_path} into IGinX succeeded.")
|
|
509
|
+
|
|
510
|
+
# divide file into chunks(default:10KB)
|
|
511
|
+
def load_file_by_chunks(self, file_path, chunk_size):
|
|
512
|
+
step = self.decide_log_step(file_path)
|
|
513
|
+
with open(file_path, 'rb') as file:
|
|
514
|
+
index = 0
|
|
515
|
+
while True:
|
|
516
|
+
chunk = file.read(chunk_size)
|
|
517
|
+
if not chunk:
|
|
518
|
+
break
|
|
519
|
+
self.process_file_chunk(chunk, file_path, index, index % step == 0)
|
|
520
|
+
index += 1
|
|
521
|
+
|
|
522
|
+
def decide_log_step(self, file_path):
|
|
523
|
+
file_size = Path(file_path).stat().st_size
|
|
524
|
+
# 100MB以内
|
|
525
|
+
if file_size < 100 * 1024 * 1024:
|
|
526
|
+
return 10 # 每10块记录一次
|
|
527
|
+
# 100MB到1GB
|
|
528
|
+
elif file_size < 1 * 1024 * 1024 * 1024:
|
|
529
|
+
return 100 # 每100块记录一次
|
|
530
|
+
# 大于1GB
|
|
531
|
+
else:
|
|
532
|
+
return 1000 # 每1000块记录一次
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
# insert file chunk data into IGinX
|
|
536
|
+
# index will be key, chunk will be value
|
|
537
|
+
def process_file_chunk(self, chunk, file_path, index, is_report):
|
|
538
|
+
file_name = os.path.basename(file_path).replace("-", "_")
|
|
539
|
+
file_dir = os.path.basename(os.path.dirname(file_path)).replace("-", "_")
|
|
540
|
+
if file_name.__contains__("-") or file_dir.__contains__("-"):
|
|
541
|
+
print(f"Warning occurred processing file {file_path}: File name: {file_name} and last dir: {file_dir}/ can't contain \"-\"")
|
|
542
|
+
print(f"\t\t \"-\" will be replaced with \"_\"")
|
|
543
|
+
file_name = file_name.replace("-", "_")
|
|
544
|
+
file_dir = file_dir.replace("-", "_")
|
|
545
|
+
data_path = file_dir + "." + str(file_name).replace(".", "_")
|
|
546
|
+
# 若干个块一报,避免大文件报太多
|
|
547
|
+
if is_report:
|
|
548
|
+
print(f"Processing #{index} file chunk and more chunks...")
|
|
549
|
+
self.insert_row_records(paths=[data_path], timestamps=[index], values_list=[[chunk]],
|
|
550
|
+
data_type_list=[DataType.BINARY])
|
|
551
|
+
|
|
552
|
+
def export_to_file(self, statement):
|
|
553
|
+
resp = self.execute_statement(statement)
|
|
554
|
+
if resp.get_export_stream_dir():
|
|
555
|
+
self.export_stream(resp)
|
|
556
|
+
if resp.get_export_csv():
|
|
557
|
+
self.export_csv(resp)
|
|
558
|
+
|
|
559
|
+
def export_stream(self, resp):
|
|
560
|
+
dir_path = resp.get_export_stream_dir()
|
|
561
|
+
|
|
562
|
+
if not os.path.exists(dir_path):
|
|
563
|
+
os.makedirs(dir_path)
|
|
564
|
+
if not os.path.isdir(dir_path):
|
|
565
|
+
raise ValueError(f"{dir_path} is not a directory!")
|
|
566
|
+
|
|
567
|
+
final_cnt = len(resp.columns())
|
|
568
|
+
columns = list(resp.columns())
|
|
569
|
+
count_map = {}
|
|
570
|
+
|
|
571
|
+
for i in range(len(columns)):
|
|
572
|
+
origin_column = columns[i]
|
|
573
|
+
if origin_column == "key":
|
|
574
|
+
columns[i] = ""
|
|
575
|
+
final_cnt -= 1
|
|
576
|
+
continue
|
|
577
|
+
|
|
578
|
+
count = count_map.get(origin_column, 0)
|
|
579
|
+
count += 1
|
|
580
|
+
count_map[origin_column] = count
|
|
581
|
+
|
|
582
|
+
# 重复的列名在列名后面加上(1),(2)...
|
|
583
|
+
if count >= 2:
|
|
584
|
+
columns[i] = os.path.join(dir_path, f"{origin_column}({count - 1})")
|
|
585
|
+
else:
|
|
586
|
+
columns[i] = os.path.join(dir_path, origin_column)
|
|
587
|
+
|
|
588
|
+
# 若将要写入的文件存在,删除之
|
|
589
|
+
if os.path.exists(columns[i]):
|
|
590
|
+
os.remove(columns[i])
|
|
591
|
+
|
|
592
|
+
while resp.has_more():
|
|
593
|
+
cache = self.cache_result_byte_array(resp, True)
|
|
594
|
+
self.export_byte_stream(cache, columns)
|
|
595
|
+
|
|
596
|
+
resp.close()
|
|
597
|
+
|
|
598
|
+
print(f"Successfully wrote {final_cnt} file(s) to directory: \"{os.path.abspath(dir_path)}\".")
|
|
599
|
+
|
|
600
|
+
def export_byte_stream(self, binary_data_list, columns):
|
|
601
|
+
for i, column in enumerate(columns):
|
|
602
|
+
if not column:
|
|
603
|
+
continue
|
|
604
|
+
|
|
605
|
+
try:
|
|
606
|
+
# 如果文件不存在,则创建并打开文件;否则,以追加模式打开文件
|
|
607
|
+
mode = 'ab' if os.path.exists(column) else 'wb'
|
|
608
|
+
with open(column, mode) as fos:
|
|
609
|
+
for value in binary_data_list:
|
|
610
|
+
# 写入对应列的数据
|
|
611
|
+
fos.write(value)
|
|
612
|
+
except IOError as e:
|
|
613
|
+
raise RuntimeError(f"Encounter an error when writing file {column}, because {e}")
|
|
614
|
+
|
|
615
|
+
def cache_result_byte_array(self, dataset, remove_key):
|
|
616
|
+
cache = []
|
|
617
|
+
row_index = 0
|
|
618
|
+
fetch_size = 1000
|
|
619
|
+
types = list(dataset.types())
|
|
620
|
+
if remove_key:
|
|
621
|
+
types.pop(0)
|
|
622
|
+
|
|
623
|
+
while dataset.has_more() and row_index < fetch_size:
|
|
624
|
+
byte_value = dataset.next_row_as_bytes(True)
|
|
625
|
+
if byte_value:
|
|
626
|
+
cache.append(byte_value)
|
|
627
|
+
row_index += 1
|
|
628
|
+
return cache
|
|
629
|
+
|
|
630
|
+
# 仿照java代码编写,未经测试,需要注意
|
|
631
|
+
def export_csv(self, resp):
|
|
632
|
+
export_csv = resp.get_export_csv()
|
|
633
|
+
|
|
634
|
+
path = export_csv.exportCsvPath
|
|
635
|
+
if not path.endswith(".csv"):
|
|
636
|
+
raise ValueError(f"The file name must end with [.csv], {path} doesn't satisfy the requirement!")
|
|
637
|
+
|
|
638
|
+
# 删除原来的csv文件,新建一个新的csv文件
|
|
639
|
+
if os.path.exists(path):
|
|
640
|
+
os.remove(path)
|
|
641
|
+
directory = os.path.dirname(path)
|
|
642
|
+
if not os.path.exists(directory):
|
|
643
|
+
os.makedirs(directory)
|
|
644
|
+
with open(path, 'w', newline='') as file: # newline='' 是为了防止在Windows上写入额外的空行
|
|
645
|
+
writer = csv.writer(file)
|
|
646
|
+
has_key = resp.columns()[0] == "key"
|
|
647
|
+
|
|
648
|
+
if export_csv.isExportHeader:
|
|
649
|
+
header_names = ["key"] if not has_key else []
|
|
650
|
+
header_names.extend(resp.columns())
|
|
651
|
+
writer.writerow(header_names)
|
|
652
|
+
|
|
653
|
+
index = 0
|
|
654
|
+
while resp.has_more():
|
|
655
|
+
index += 1
|
|
656
|
+
print(f"Writing #{index} 1000 records into file: {os.path.abspath(path)}...")
|
|
657
|
+
cache = self.cache_result(resp, True)
|
|
658
|
+
writer.writerows(cache)
|
|
659
|
+
|
|
660
|
+
print(f"Successfully wrote csv file: \"{os.path.abspath(path)}\".")
|
|
661
|
+
|
|
662
|
+
def cache_result(self, dataset, skip_header):
|
|
663
|
+
has_key = dataset.columns()[0] == "key"
|
|
664
|
+
cache = []
|
|
665
|
+
if not skip_header:
|
|
666
|
+
cache.append(dataset.columns())
|
|
667
|
+
|
|
668
|
+
row_index = 0
|
|
669
|
+
fetch_size = 1000
|
|
670
|
+
|
|
671
|
+
while dataset.has_more() and row_index < fetch_size:
|
|
672
|
+
row = dataset.next()
|
|
673
|
+
if row:
|
|
674
|
+
str_row = []
|
|
675
|
+
if has_key:
|
|
676
|
+
key = datetime.fromtimestamp(row[0]).strftime("%Y-%m-%d %H:%M:%S")
|
|
677
|
+
str_row.append(key)
|
|
678
|
+
for i in range(1, len(row)):
|
|
679
|
+
if isinstance(row[i], bytes):
|
|
680
|
+
str_row.append(row[i].decode("utf-8"))
|
|
681
|
+
else:
|
|
682
|
+
str_row.append(str(row[i]))
|
|
683
|
+
else:
|
|
684
|
+
str_row = [value.decode("utf-8") if isinstance(value, bytes) else str(value) for value in row]
|
|
685
|
+
cache.append(str_row)
|
|
686
|
+
row_index += 1
|
|
687
|
+
|
|
688
|
+
return cache
|
|
689
|
+
|
|
690
|
+
def get_debug_info(self, payload, typ):
|
|
691
|
+
req = DebugInfoReq(payload=payload, payloadType=typ)
|
|
692
|
+
resp = self.__client.debugInfo(req)
|
|
693
|
+
Session.verify_status(resp.status)
|
|
694
|
+
return resp.payload
|
|
695
|
+
|
|
696
|
+
def _fetch(self, query_id, fetch_size):
|
|
697
|
+
req = FetchResultsReq(sessionId=self.__session_id, queryId=query_id, fetchSize=fetch_size)
|
|
698
|
+
resp = self.__client.fetchResults(req)
|
|
699
|
+
Session.verify_status(resp.status)
|
|
700
|
+
return (resp.hasMoreResults, resp.queryDataSet)
|
|
701
|
+
|
|
702
|
+
def _close_statement(self, query_id):
|
|
703
|
+
req = CloseStatementReq(sessionId=self.__session_id, queryId=query_id)
|
|
704
|
+
status = self.__client.closeStatement(req)
|
|
705
|
+
Session.verify_status(status)
|
|
706
|
+
|
|
707
|
+
@staticmethod
|
|
708
|
+
def verify_status(status):
|
|
709
|
+
if status.code != Session.SUCCESS_CODE:
|
|
710
|
+
raise RuntimeError("Error occurs: " + status.message)
|
|
711
|
+
|
|
712
|
+
@staticmethod
|
|
713
|
+
def merge_and_sort_paths(paths):
|
|
714
|
+
for path in paths:
|
|
715
|
+
if path == '*':
|
|
716
|
+
return ['*']
|
|
717
|
+
|
|
718
|
+
prefixes = []
|
|
719
|
+
for path in paths:
|
|
720
|
+
index = path.find('*')
|
|
721
|
+
if index != -1:
|
|
722
|
+
prefixes.append(path[:index])
|
|
723
|
+
|
|
724
|
+
if len(prefixes) == 0:
|
|
725
|
+
return sorted(paths)
|
|
726
|
+
|
|
727
|
+
merged_paths = []
|
|
728
|
+
for path in paths:
|
|
729
|
+
if '*' not in path:
|
|
730
|
+
skip = False
|
|
731
|
+
for prefix in prefixes:
|
|
732
|
+
if path.startswith(prefix):
|
|
733
|
+
skip = True
|
|
734
|
+
break
|
|
735
|
+
if skip:
|
|
736
|
+
continue
|
|
737
|
+
merged_paths.append(path)
|
|
738
|
+
|
|
739
|
+
return sorted(merged_paths)
|