-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathdatabase.py
3365 lines (2849 loc) · 124 KB
/
database.py
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
__all__ = [
"StandardDatabase",
"AsyncDatabase",
"BatchDatabase",
"OverloadControlDatabase",
"TransactionDatabase",
]
from datetime import datetime
from numbers import Number
from typing import Any, Dict, List, Optional, Sequence, Union
from warnings import warn
from arango.api import ApiGroup
from arango.aql import AQL
from arango.backup import Backup
from arango.cluster import Cluster
from arango.collection import StandardCollection
from arango.connection import Connection
from arango.exceptions import (
AnalyzerCreateError,
AnalyzerDeleteError,
AnalyzerGetError,
AnalyzerListError,
AsyncJobClearError,
AsyncJobListError,
CollectionCreateError,
CollectionDeleteError,
CollectionListError,
DatabaseCompactError,
DatabaseCreateError,
DatabaseDeleteError,
DatabaseListError,
DatabasePropertiesError,
DatabaseSupportInfoError,
GraphCreateError,
GraphDeleteError,
GraphListError,
JWTSecretListError,
JWTSecretReloadError,
PermissionGetError,
PermissionListError,
PermissionResetError,
PermissionUpdateError,
ServerAvailableOptionsGetError,
ServerCurrentOptionsGetError,
ServerDetailsError,
ServerEchoError,
ServerEncryptionError,
ServerEngineError,
ServerExecuteError,
ServerLicenseGetError,
ServerLicenseSetError,
ServerLogLevelError,
ServerLogLevelResetError,
ServerLogLevelSetError,
ServerLogSettingError,
ServerLogSettingSetError,
ServerMetricsError,
ServerModeError,
ServerModeSetError,
ServerReadLogError,
ServerReloadRoutingError,
ServerRequiredDBVersionError,
ServerRoleError,
ServerRunTestsError,
ServerShutdownError,
ServerShutdownProgressError,
ServerStatisticsError,
ServerStatusError,
ServerTimeError,
ServerTLSError,
ServerTLSReloadError,
ServerVersionError,
TaskCreateError,
TaskDeleteError,
TaskGetError,
TaskListError,
TransactionExecuteError,
TransactionListError,
UserCreateError,
UserDeleteError,
UserGetError,
UserListError,
UserReplaceError,
UserUpdateError,
ViewCreateError,
ViewDeleteError,
ViewGetError,
ViewListError,
ViewRenameError,
ViewReplaceError,
ViewUpdateError,
)
from arango.executor import (
AsyncApiExecutor,
BatchApiExecutor,
DefaultApiExecutor,
OverloadControlApiExecutor,
TransactionApiExecutor,
)
from arango.formatter import (
format_body,
format_database,
format_server_status,
format_tls,
format_view,
)
from arango.foxx import Foxx
from arango.graph import Graph
from arango.job import BatchJob
from arango.pregel import Pregel
from arango.replication import Replication
from arango.request import Request
from arango.response import Response
from arango.result import Result
from arango.typings import Json, Jsons, Params
from arango.utils import get_col_name
from arango.wal import WAL
class Database(ApiGroup):
"""Base class for Database API wrappers."""
def __getitem__(self, name: str) -> StandardCollection:
"""Return the collection API wrapper.
:param name: Collection name.
:type name: str
:return: Collection API wrapper.
:rtype: arango.collection.StandardCollection
"""
return self.collection(name)
def _get_col_by_doc(self, document: Union[str, Json]) -> StandardCollection:
"""Return the collection of the given document.
:param document: Document ID or body with "_id" field.
:type document: str | dict
:return: Collection API wrapper.
:rtype: arango.collection.StandardCollection
:raise arango.exceptions.DocumentParseError: On malformed document.
"""
return self.collection(get_col_name(document))
@property
def name(self) -> str:
"""Return database name.
:return: Database name.
:rtype: str
"""
return self.db_name
@property
def aql(self) -> AQL:
"""Return AQL (ArangoDB Query Language) API wrapper.
:return: AQL API wrapper.
:rtype: arango.aql.AQL
"""
return AQL(self._conn, self._executor)
@property
def wal(self) -> WAL:
"""Return WAL (Write-Ahead Log) API wrapper.
:return: WAL API wrapper.
:rtype: arango.wal.WAL
"""
return WAL(self._conn, self._executor)
@property
def foxx(self) -> Foxx:
"""Return Foxx API wrapper.
:return: Foxx API wrapper.
:rtype: arango.foxx.Foxx
"""
return Foxx(self._conn, self._executor)
@property
def pregel(self) -> Pregel:
"""Return Pregel API wrapper.
:return: Pregel API wrapper.
:rtype: arango.pregel.Pregel
"""
return Pregel(self._conn, self._executor)
@property
def replication(self) -> Replication:
"""Return Replication API wrapper.
:return: Replication API wrapper.
:rtype: arango.replication.Replication
"""
return Replication(self._conn, self._executor)
@property
def cluster(self) -> Cluster: # pragma: no cover
"""Return Cluster API wrapper.
:return: Cluster API wrapper.
:rtype: arango.cluster.Cluster
"""
return Cluster(self._conn, self._executor)
@property
def backup(self) -> Backup:
"""Return Backup API wrapper.
:return: Backup API wrapper.
:rtype: arango.backup.Backup
"""
return Backup(self._conn, self._executor)
def properties(self) -> Result[Json]:
"""Return database properties.
:return: Database properties.
:rtype: dict
:raise arango.exceptions.DatabasePropertiesError: If retrieval fails.
"""
request = Request(
method="get",
endpoint="/_api/database/current",
)
def response_handler(resp: Response) -> Json:
if not resp.is_success:
raise DatabasePropertiesError(resp, request)
return format_database(resp.body["result"])
return self._execute(request, response_handler)
def execute(self, command: str) -> Result[Any]:
"""Execute raw Javascript command on the server.
Executes the JavaScript code in the body on the server as
the body of a function with no arguments. If you have a
return statement then the return value you produce will be returned
as 'application/json'.
NOTE: this method endpoint will only be usable if the server
was started with the option `--javascript.allow-admin-execute true`.
The default value of this option is false, which disables the execution
of user-defined code and disables this API endpoint entirely.
This is also the recommended setting for production.
:param command: Javascript command to execute.
:type command: str
:return: Return value of **command**, if any.
:rtype: Any
:raise arango.exceptions.ServerExecuteError: If execution fails.
"""
request = Request(method="post", endpoint="/_admin/execute", data=command)
def response_handler(resp: Response) -> Any:
if not resp.is_success:
raise ServerExecuteError(resp, request)
return resp.body
return self._execute(request, response_handler)
def execute_transaction(
self,
command: str,
params: Optional[Json] = None,
read: Optional[Sequence[str]] = None,
write: Optional[Sequence[str]] = None,
sync: Optional[bool] = None,
timeout: Optional[Number] = None,
max_size: Optional[int] = None,
allow_implicit: Optional[bool] = None,
intermediate_commit_count: Optional[int] = None,
intermediate_commit_size: Optional[int] = None,
allow_dirty_read: bool = False,
) -> Result[Any]:
"""Execute raw Javascript command in transaction.
:param command: Javascript command to execute.
:type command: str
:param read: Names of collections read during transaction. If parameter
**allow_implicit** is set to True, any undeclared read collections
are loaded lazily.
:type read: [str] | None
:param write: Names of collections written to during transaction.
Transaction fails on undeclared write collections.
:type write: [str] | None
:param params: Optional parameters passed into the Javascript command.
:type params: dict | None
:param sync: Block until operation is synchronized to disk.
:type sync: bool | None
:param timeout: Timeout for waiting on collection locks. If set to 0,
ArangoDB server waits indefinitely. If not set, system default
value is used.
:type timeout: int | None
:param max_size: Max transaction size limit in bytes.
:type max_size: int | None
:param allow_implicit: If set to True, undeclared read collections are
loaded lazily. If set to False, transaction fails on any undeclared
collections.
:type allow_implicit: bool | None
:param intermediate_commit_count: Max number of operations after which
an intermediate commit is performed automatically.
:type intermediate_commit_count: int | None
:param intermediate_commit_size: Max size of operations in bytes after
which an intermediate commit is performed automatically.
:type intermediate_commit_size: int | None
:param allow_dirty_read: Allow reads from followers in a cluster.
:type allow_dirty_read: bool | None
:return: Return value of **command**.
:rtype: Any
:raise arango.exceptions.TransactionExecuteError: If execution fails.
"""
collections: Json = {"allowImplicit": allow_implicit}
if read is not None:
collections["read"] = read
if write is not None:
collections["write"] = write
data: Json = {"action": command}
if collections:
data["collections"] = collections
if params is not None:
data["params"] = params
if timeout is not None:
data["lockTimeout"] = timeout
if sync is not None:
data["waitForSync"] = sync
if max_size is not None:
data["maxTransactionSize"] = max_size
if intermediate_commit_count is not None:
data["intermediateCommitCount"] = intermediate_commit_count
if intermediate_commit_size is not None:
data["intermediateCommitSize"] = intermediate_commit_size
request = Request(
method="post",
endpoint="/_api/transaction",
data=data,
headers={"x-arango-allow-dirty-read": "true"} if allow_dirty_read else None,
)
def response_handler(resp: Response) -> Any:
if not resp.is_success:
raise TransactionExecuteError(resp, request)
return resp.body.get("result")
return self._execute(request, response_handler)
def list_transactions(self) -> Result[Jsons]:
"""Return the list of running stream transactions.
:return: The list of transactions, with each transaction
containing an "id" and a "state" field.
:rtype: List[Dict[str, Any]]
:raise arango.exceptions.TransactionListError: If retrieval fails.
"""
request = Request(method="get", endpoint="/_api/transaction")
def response_handler(resp: Response) -> Jsons:
if not resp.is_success:
raise TransactionListError(resp, request)
result: Jsons = resp.body["transactions"]
return result
return self._execute(request, response_handler)
def version(self, details: bool = False) -> Result[Any]:
"""Return ArangoDB server version.
:param details: Return more detailed version output
:type details: bool | None
:return: Server version.
:rtype: str
:raise arango.exceptions.ServerVersionError: If retrieval fails.
"""
request = Request(
method="get", endpoint="/_api/version", params={"details": details}
)
def response_handler(resp: Response) -> Any:
if not resp.is_success:
raise ServerVersionError(resp, request)
if not details:
return str(resp.body["version"])
else:
return resp.body
return self._execute(request, response_handler)
def details(self) -> Result[Json]:
"""Return ArangoDB server details.
:return: Server details.
:rtype: dict
:raise arango.exceptions.ServerDetailsError: If retrieval fails.
"""
request = Request(
method="get", endpoint="/_api/version", params={"details": True}
)
def response_handler(resp: Response) -> Json:
if resp.is_success:
result: Json = resp.body["details"]
return result
raise ServerDetailsError(resp, request)
return self._execute(request, response_handler)
def license(self) -> Result[Json]:
"""View the license information and status of an
Enterprise Edition instance. Can be called on
single servers, Coordinators, and DB-Servers.
:return: Server license.
:rtype: dict
:raise arango.exceptions.ServerLicenseGetError: If retrieval fails.
"""
request = Request(method="get", endpoint="/_admin/license")
def response_handler(resp: Response) -> Json:
if resp.is_success:
result: Json = resp.body
return result
raise ServerLicenseGetError(resp, request)
return self._execute(request, response_handler)
def set_license(self, license: str, force: bool = False) -> Result[Json]:
"""Set a new license for an Enterprise Edition
instance. Can be called on single servers, Coordinators,
and DB-Servers.
:param license: The Base64-encoded license string.
:type license: str
:param force: If set to True, the new license will be set even if
it expires sooner than the current license.
:type force: bool
:return: Server license.
:rtype: dict
:raise arango.exceptions.ServerLicenseError: If retrieval fails.
"""
request = Request(
method="put",
endpoint="/_admin/license",
params={"force": force},
data=license,
)
def response_handler(resp: Response) -> Json:
if resp.is_success:
result: Json = resp.body
return result
raise ServerLicenseSetError(resp, request)
return self._execute(request, response_handler)
def status(self) -> Result[Json]:
"""Return ArangoDB server status.
:return: Server status.
:rtype: dict
:raise arango.exceptions.ServerStatusError: If retrieval fails.
"""
request = Request(
method="get",
endpoint="/_admin/status",
)
def response_handler(resp: Response) -> Json:
if not resp.is_success:
raise ServerStatusError(resp, request)
return format_server_status(resp.body)
return self._execute(request, response_handler)
def compact(
self,
change_level: Optional[bool] = None,
compact_bottom_most_level: Optional[bool] = None,
) -> Result[Json]:
"""Compact all databases.
NOTE: This command can cause a full rewrite of all data in all databases,
which may take very long for large databases. It should thus only be used with
care and only when additional I/O load can be tolerated for a prolonged time.
This method can be used to reclaim disk space after substantial data deletions
have taken place, by compacting the entire database system data.
This method requires superuser access.
:param change_level: Whether or not compacted data should be moved to
the minimum possible level. Default value is False.
:type change_level: bool | None
:param compact_bottom_most_level: Whether or not to compact the
bottom-most level of data. Default value is False.
:type compact_bottom_most_level: bool | None
:return: Collection compact.
:rtype: dict
:raise arango.exceptions.CollectionCompactError: If retrieval fails.
"""
data = {}
if change_level is not None:
data["changeLevel"] = change_level
if compact_bottom_most_level is not None:
data["compactBottomMostLevel"] = compact_bottom_most_level
request = Request(method="put", endpoint="/_admin/compact", data=data)
def response_handler(resp: Response) -> Json:
if resp.is_success:
return format_body(resp.body)
raise DatabaseCompactError(resp, request)
return self._execute(request, response_handler)
def required_db_version(self) -> Result[str]:
"""Return required version of target database.
:return: Required version of target database.
:rtype: str
:raise arango.exceptions.ServerRequiredDBVersionError: If retrieval fails.
"""
request = Request(method="get", endpoint="/_admin/database/target-version")
def response_handler(resp: Response) -> str:
if resp.is_success:
return str(resp.body["version"])
raise ServerRequiredDBVersionError(resp, request)
return self._execute(request, response_handler)
def engine(self) -> Result[Json]:
"""Return the database engine details.
:return: Database engine details.
:rtype: dict
:raise arango.exceptions.ServerEngineError: If retrieval fails.
"""
request = Request(method="get", endpoint="/_api/engine")
def response_handler(resp: Response) -> Json:
if resp.is_success:
return format_body(resp.body)
raise ServerEngineError(resp, request)
return self._execute(request, response_handler)
def statistics(self, description: bool = False) -> Result[Json]:
"""Return server statistics.
:return: Server statistics.
:rtype: dict
:raise arango.exceptions.ServerStatisticsError: If retrieval fails.
"""
if description:
endpoint = "/_admin/statistics-description"
else:
endpoint = "/_admin/statistics"
request = Request(method="get", endpoint=endpoint)
def response_handler(resp: Response) -> Json:
if resp.is_success:
return format_body(resp.body)
raise ServerStatisticsError(resp, request)
return self._execute(request, response_handler)
def role(self) -> Result[str]:
"""Return server role.
:return: Server role. Possible values are "SINGLE" (server which is not
in a cluster), "COORDINATOR" (cluster coordinator), "PRIMARY",
"SECONDARY", "AGENT" (Agency node in a cluster) or "UNDEFINED".
:rtype: str
:raise arango.exceptions.ServerRoleError: If retrieval fails.
"""
request = Request(method="get", endpoint="/_admin/server/role")
def response_handler(resp: Response) -> str:
if resp.is_success:
return str(resp.body["role"])
raise ServerRoleError(resp, request)
return self._execute(request, response_handler)
def mode(self) -> Result[str]:
"""Return the server mode (default or read-only)
In a read-only server, all write operations will fail
with an error code of 1004 (ERROR_READ_ONLY). Creating or dropping
databases and collections will also fail with error code 11 (ERROR_FORBIDDEN).
:return: Server mode. Possible values are "default" or "readonly".
:rtype: str
:raise arango.exceptions.ServerModeError: If retrieval fails.
"""
request = Request(method="get", endpoint="/_admin/server/mode")
def response_handler(resp: Response) -> str:
if resp.is_success:
return str(resp.body["mode"])
raise ServerModeError(resp, request)
return self._execute(request, response_handler)
def set_mode(self, mode: str) -> Result[Json]:
"""Set the server mode to read-only or default.
Update mode information about a server. The JSON response will
contain a field mode with the value readonly or default.
In a read-only server all write operations will fail with an error
code of 1004 (ERROR_READ_ONLY). Creating or dropping of databases
and collections will also fail with error code 11 (ERROR_FORBIDDEN).
This is a protected API. It requires authentication and administrative
server rights.
:param mode: Server mode. Possible values are "default" or "readonly".
:type mode: str
:return: Server mode.
:rtype: str
:raise arango.exceptions.ServerModeSetError: If set fails.
"""
request = Request(
method="put", endpoint="/_admin/server/mode", data={"mode": mode}
)
def response_handler(resp: Response) -> Json:
if resp.is_success:
return format_body(resp.body)
raise ServerModeSetError(resp, request)
return self._execute(request, response_handler)
def time(self) -> Result[datetime]:
"""Return server system time.
:return: Server system time.
:rtype: datetime.datetime
:raise arango.exceptions.ServerTimeError: If retrieval fails.
"""
request = Request(method="get", endpoint="/_admin/time")
def response_handler(resp: Response) -> datetime:
if not resp.is_success:
raise ServerTimeError(resp, request)
return datetime.fromtimestamp(resp.body["time"])
return self._execute(request, response_handler)
def echo(self, body: Optional[Any] = None) -> Result[Json]:
"""Return details of the last request (e.g. headers, payload),
or echo the given request body.
:param body: The body of the request. Can be of any type
and is simply forwarded. If not set, the details of the last
request are returned.
:type body: dict | list | str | int | float | None
:return: Details of the last request.
:rtype: dict
:raise arango.exceptions.ServerEchoError: If retrieval fails.
"""
request = (
Request(method="get", endpoint="/_admin/echo")
if body is None
else Request(method="post", endpoint="/_admin/echo", data=body)
)
def response_handler(resp: Response) -> Json:
if not resp.is_success:
raise ServerEchoError(resp, request)
result: Json = resp.body
return result
return self._execute(request, response_handler)
def shutdown(self, soft: bool = False) -> Result[bool]: # pragma: no cover
"""Initiate server shutdown sequence.
:param soft: If set to true, this initiates a soft shutdown. This is only
available on Coordinators. When issued, the Coordinator tracks a number
of ongoing operations, waits until all have finished, and then shuts
itself down normally. It will still accept new operations.
:type soft: bool
:return: True if the server was shutdown successfully.
:rtype: bool
:raise arango.exceptions.ServerShutdownError: If shutdown fails.
"""
request = Request(
method="delete", endpoint="/_admin/shutdown", params={"soft": soft}
)
def response_handler(resp: Response) -> bool:
if not resp.is_success:
raise ServerShutdownError(resp, request)
return True
return self._execute(request, response_handler)
def shutdown_progress(self) -> Result[Json]: # pragma: no cover
"""Query the soft shutdown progress. This call reports progress about a
soft Coordinator shutdown (DELETE /_admin/shutdown?soft=true). This API
is only available on Coordinators.
:return: Information about the shutdown progress.
:rtype: dict
:raise arango.exceptions.ServerShutdownError: If shutdown fails.
"""
request = Request(method="get", endpoint="/_admin/shutdown")
def response_handler(resp: Response) -> Json:
if not resp.is_success:
raise ServerShutdownProgressError(resp, request)
result: Json = resp.body
return result
return self._execute(request, response_handler)
def run_tests(self, tests: Sequence[str]) -> Result[Json]: # pragma: no cover
"""Run available unittests on the server.
:param tests: List of files containing the test suites.
:type tests: [str]
:return: Test results.
:rtype: dict
:raise arango.exceptions.ServerRunTestsError: If execution fails.
"""
request = Request(method="post", endpoint="/_admin/test", data={"tests": tests})
def response_handler(resp: Response) -> Json:
if not resp.is_success:
raise ServerRunTestsError(resp, request)
result: Json = resp.body
return result
return self._execute(request, response_handler)
def read_log(
self,
upto: Optional[Union[int, str]] = None,
level: Optional[Union[int, str]] = None,
start: Optional[int] = None,
size: Optional[int] = None,
offset: Optional[int] = None,
search: Optional[str] = None,
sort: Optional[str] = None,
) -> Result[Json]:
"""Read the global log from server. This method is deprecated
in ArangoDB 3.8 and will be removed in a future version
of the driver. Use :func:`arango.database.Database.read_log_entries`
instead.
:param upto: Return the log entries up to the given level (mutually
exclusive with parameter **level**). Allowed values are "fatal",
"error", "warning", "info" (default) and "debug".
:type upto: int | str
:param level: Return the log entries of only the given level (mutually
exclusive with **upto**). Allowed values are "fatal", "error",
"warning", "info" (default) and "debug".
:type level: int | str
:param start: Return the log entries whose ID is greater or equal to
the given value.
:type start: int
:param size: Restrict the size of the result to the given value. This
can be used for pagination.
:type size: int
:param offset: Number of entries to skip (e.g. for pagination).
:type offset: int
:param search: Return only the log entries containing the given text.
:type search: str
:param sort: Sort the log entries according to the given fashion, which
can be "sort" or "desc".
:type sort: str
:return: Server log entries.
:rtype: dict
:raise arango.exceptions.ServerReadLogError: If read fails.
"""
m = "read_log() is deprecated in ArangoDB 3.8 and will be removed in a future version of the driver. Use read_log_entries() instead." # noqa: E501
warn(m, DeprecationWarning, stacklevel=2)
params = dict()
if upto is not None:
params["upto"] = upto
if level is not None:
params["level"] = level
if start is not None:
params["start"] = start
if size is not None:
params["size"] = size
if offset is not None:
params["offset"] = offset
if search is not None:
params["search"] = search
if sort is not None:
params["sort"] = sort
request = Request(method="get", endpoint="/_admin/log", params=params)
def response_handler(resp: Response) -> Json:
if not resp.is_success:
raise ServerReadLogError(resp, request)
result: Json = resp.body
if "totalAmount" in result:
resp.body["total_amount"] = resp.body.pop("totalAmount")
return result
return self._execute(request, response_handler)
def read_log_entries(
self,
upto: Optional[Union[int, str]] = None,
level: Optional[Union[int, str]] = None,
start: Optional[int] = None,
size: Optional[int] = None,
offset: Optional[int] = None,
search: Optional[str] = None,
sort: Optional[str] = None,
server_id: Optional[str] = None,
) -> Result[Json]:
"""Read the global log from server.
:param upto: Return the log entries up to the given level (mutually
exclusive with parameter **level**). Allowed values are "fatal",
"error", "warning", "info" (default) and "debug".
:type upto: int | str
:param level: Return the log entries of only the given level (mutually
exclusive with **upto**). Allowed values are "fatal", "error",
"warning", "info" (default) and "debug".
:type level: int | str
:param start: Return the log entries whose ID is greater or equal to
the given value.
:type start: int
:param size: Restrict the size of the result to the given value. This
can be used for pagination.
:type size: int
:param offset: Number of entries to skip (e.g. for pagination).
:type offset: int
:param search: Return only the log entries containing the given text.
:type search: str
:param sort: Sort the log entries according to the given fashion, which
can be "sort" or "desc".
:type sort: str
:param server_id: Returns all log entries of the specified server.
All other query parameters remain valid. If no serverId is given,
the asked server will reply. This parameter is only meaningful
on Coordinators.
:type server_id: str
:return: Server log entries.
:rtype: dict
:raise arango.exceptions.ServerReadLogError: If read fails.
"""
params = dict()
if upto is not None:
params["upto"] = upto
if level is not None:
params["level"] = level
if start is not None:
params["start"] = start
if size is not None:
params["size"] = size
if offset is not None:
params["offset"] = offset
if search is not None:
params["search"] = search
if sort is not None:
params["sort"] = sort
if server_id is not None:
params["serverId"] = server_id
request = Request(method="get", endpoint="/_admin/log/entries", params=params)
def response_handler(resp: Response) -> Json:
if not resp.is_success:
raise ServerReadLogError(resp, request)
result: Json = resp.body
return result
return self._execute(request, response_handler)
def log_settings(self) -> Result[Json]:
"""Return the structured log settings.
:return: Current log settings. False values are not returned.
:rtype: dict
"""
request = Request(method="get", endpoint="/_admin/log/structured")
def response_handler(resp: Response) -> Json:
if not resp.is_success:
raise ServerLogSettingError(resp, request)
result: Json = resp.body
return result
return self._execute(request, response_handler)
def set_log_settings(self, **kwargs: Dict[str, Any]) -> Result[Json]:
"""Set the structured log settings.
This method takes arbitrary keyword arguments where the keys are the
structured log parameters and the values are true or false, for either
enabling or disabling the parameters.
.. code-block:: python
arango.set_log_settings(
database=True,
url=True,
username=False,
)
:param kwargs: Structured log parameters.
:type kwargs: Dict[str, Any]
:return: New log settings. False values are not returned.
:rtype: dict
"""
request = Request(method="put", endpoint="/_admin/log/structured", data=kwargs)
def response_handler(resp: Response) -> Json:
if not resp.is_success:
raise ServerLogSettingSetError(resp, request)
result: Json = resp.body
return result
return self._execute(request, response_handler)
def log_levels(
self, server_id: Optional[str] = None, with_appenders: Optional[bool] = None
) -> Result[Json]:
"""Return current logging levels.
:param server_id: Forward log level to a specific server. This makes it
easier to adjust the log levels in clusters because DB-Servers require
JWT authentication whereas Coordinators also support authentication
using usernames and passwords.
:type server_id: str
:param with_appenders: Include appenders in the response.
:type with_appenders: bool
:return: Current logging levels.
:rtype: dict
"""
params: Params = {}
if server_id is not None:
params["serverId"] = server_id
if with_appenders is not None:
params["withAppenders"] = with_appenders
request = Request(method="get", endpoint="/_admin/log/level", params=params)
def response_handler(resp: Response) -> Json:
if not resp.is_success:
raise ServerLogLevelError(resp, request)
result: Json = resp.body
return result
return self._execute(request, response_handler)
def set_log_levels(
self,
server_id: Optional[str] = None,
with_appenders: Optional[bool] = None,
**kwargs: Dict[str, Any],
) -> Result[Json]:
"""Set the logging levels.
This method takes arbitrary keyword arguments where the keys are the
logger names and the values are the logging levels. For example:
.. code-block:: python
arango.set_log_levels(
agency='DEBUG',
collector='INFO',
threads='WARNING'
)
Keys that are not valid logger names are ignored.
:param server_id: Forward log level to a specific server. This makes it
easier to adjust the log levels in clusters because DB-Servers require
JWT authentication whereas Coordinators also support authentication
using usernames and passwords.
:type server_id: str | None
:param with_appenders: Include appenders in the request.
:type with_appenders: bool | None
:param kwargs: Logging levels.
:type kwargs: Dict[str, Any]
:return: New logging levels.
:rtype: dict