forked from eth-cscs/pyfirecrest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.py
More file actions
1874 lines (1642 loc) · 64.4 KB
/
Client.py
File metadata and controls
1874 lines (1642 loc) · 64.4 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
#
# Copyright (c) 2024, ETH Zurich. All rights reserved.
#
# Please, refer to the LICENSE file in the root directory.
# SPDX-License-Identifier: BSD-3-Clause
#
from __future__ import annotations
import aiofiles
import asyncio
import httpx
import json
import logging
import os
import pathlib
import ssl
from packaging.version import Version, parse
from streamer import streamer_client as cli
from typing import Any, Optional, List
from firecrest.utilities import (
parse_retry_after,
part_checksum_xml,
sched_state_completed,
sched_state_running,
time_block,
)
from firecrest.FirecrestException import (
FirecrestException,
JobTimeoutException,
MultipartUploadException,
NotImplementedOnAPIversion,
TransferJobFailedException,
TransferJobTimeoutException,
UnexpectedStatusException,
)
logger = logging.getLogger(__name__)
# This function is temporarily here
def handle_response(response):
print("\nResponse status code:")
print(response.status_code)
print("\nResponse headers:")
print(json.dumps(dict(response.headers), indent=4))
print("\nResponse json:")
try:
print(json.dumps(response.json(), indent=4))
except json.JSONDecodeError:
print("-")
def sleep_generator():
yield 0.2
value = 0.5
while True:
yield value
# Double the value for each iteration, up to 2 minutes
if value < 60:
value *= 2
class AsyncExternalTransfer:
async def wait_for_transfer_job(self, timeout=None):
await self._client._wait_for_transfer_job(
self._transfer_info,
timeout=timeout
)
async def wait_for_streamer_job_to_listen(self):
job_id = self._transfer_info.get("transferJob", {}).get("jobId")
if job_id is None:
raise MultipartUploadException(
self._transfer_info,
"Could not find transfer job ID in the transfer info"
)
system_name = self._transfer_info.get("transferJob", {}).get("system")
if system_name is None:
raise MultipartUploadException(
self._transfer_info,
"Could not find transfer job system name in the transfer info"
)
for i in sleep_generator():
try:
job = await self._client.job_info(system_name, job_id)
except FirecrestException as e:
if (
e.responses[-1].status_code == 404 and
"Job not found" in e.responses[-1].json()['message']
):
self._client.log(
logging.DEBUG,
f"Job {job_id} information is not yet available, will "
f"sleep for {i} seconds."
)
await asyncio.sleep(i)
continue
else:
raise e
state = job[0]["status"]["state"]
if isinstance(state, list):
state = ",".join(state)
if sched_state_running(state):
self._client.log(
logging.DEBUG,
f"Job {job_id} is running with state: {state}."
)
break
if sched_state_completed(state):
raise MultipartUploadException(
self._transfer_info,
f"Job {job_id} completed before listening for "
f"connections. Current state: {state}."
)
self._client.log(
logging.DEBUG,
f"Job {job_id} state is {state}. Will sleep for {i} seconds."
)
await asyncio.sleep(i)
class AsyncExternalUpload(AsyncExternalTransfer):
def __init__(self, client, transfer_info, local_file):
self._client = client
self._local_file = local_file
self._transfer_info = transfer_info
self._all_tags = []
# Chunk size for the multipart upload. Default is 64MB.
self.chunk_size = 64 * 1024 * 1024 # 64MB
self._total_file_size = os.path.getsize(local_file)
@property
def transfer_data(self):
return self._transfer_info
async def upload_file_to_stage(self):
urls = self._transfer_info.get("partsUploadUrls")
if urls is None:
urls = self._transfer_info.get(
"transferDirectives", {}
).get("parts_upload_urls")
if urls is None:
raise MultipartUploadException(
self._transfer_info,
"Could not find parts upload URLs in the transfer info"
)
await asyncio.gather(
*[
self._upload_part(
upload_url,
index,
) for index, upload_url in enumerate(urls)
]
)
# S3 complains when tags are not sorted
self._all_tags.sort(key=lambda x: x['PartNumber'])
checksum = part_checksum_xml(self._all_tags)
await self._complete_upload(
checksum
)
async def _upload_part(self, url, index):
chunk_size = self._transfer_info.get("maxPartSize")
if chunk_size is None:
chunk_size = self._transfer_info.get(
"transferDirectives", {}
).get("max_part_size")
if chunk_size is None:
raise MultipartUploadException(
self._transfer_info,
"Could not find chunk size in the transfer info"
)
async def chunk_reader(f, c):
i = 0
while True:
next_chunk = c if i + c <= chunk_size else chunk_size - i
i += next_chunk
data = await f.read(next_chunk)
if not data:
break
yield data
start = index * chunk_size
if start + chunk_size > self._total_file_size:
content_length = self._total_file_size - start
else:
content_length = chunk_size
async with self._client._upload_semaphore:
self._client.log(
logging.DEBUG,
f"Uploading part {index + 1} to {url}"
)
async with aiofiles.open(self._local_file, "rb") as f:
await f.seek(start)
resp = await self._client._session.put(
url=url,
content=chunk_reader(f, self.chunk_size),
timeout=None,
headers={
"Content-Length": str(content_length)
}
)
if resp.status_code >= 400:
raise MultipartUploadException(
self._transfer_info,
f"Failed to upload part {index + 1}: "
f"{resp.status_code}: {resp.text}"
)
self._client.log(
logging.DEBUG,
f"Uploaded part {index + 1} to {url}"
)
e_tag = resp.headers['ETag']
self._all_tags.append({
'ETag': e_tag,
'PartNumber': index + 1
})
async def _complete_upload(self, checksum):
url = self._transfer_info.get("completeMultipartUploadUrl")
if url is None:
url = self._transfer_info.get(
"transferDirectives", {}
).get("complete_upload_url")
if url is None:
raise MultipartUploadException(
self._transfer_info,
"Could not find complete upload URL in the transfer info"
)
self._client.log(
logging.DEBUG,
f"Finishing upload of file {self._local_file} to {url}"
)
resp = await self._client._session.post(
url=url,
data=checksum
)
if resp.status_code >= 400:
raise MultipartUploadException(
self._transfer_info,
f"Failed to finish upload: {resp.status_code}: {resp.text}"
)
async def upload_file_streamer(self):
coordinates = self._transfer_info.get(
"transferDirectives", {}
).get("coordinates")
if coordinates is None:
raise MultipartUploadException(
self._transfer_info,
"Could not find upload coordinates in the transfer info"
)
self._client.log(
logging.DEBUG,
f"Uploading file {self._local_file} with `{coordinates}` "
f"coordinates"
)
config = cli.set_coordinates(coordinates)
config.target = self._local_file
await cli.client_send(config)
self._client.log(
logging.DEBUG,
f"Uploaded file {self._local_file} to {coordinates} "
f"using Streamer client"
)
class AsyncExternalDownload(AsyncExternalTransfer):
def __init__(self, client, transfer_info, file_path):
self._client = client
self._transfer_info = transfer_info
self._file_path = file_path
# Chunk size for the multipart download. Default is 64MB.
self.chunk_size = 64 * 1024 * 1024 # 64MB
@property
def transfer_data(self):
return self._transfer_info
async def download_file_from_stage(self, file_path=None):
file_name = file_path or self._file_path
download_url = self._transfer_info.get("downloadUrl")
if download_url is None:
download_url = self._transfer_info.get(
"transferDirectives", {}
).get("download_url")
if download_url is None:
raise MultipartUploadException(
self._transfer_info,
"Could not find download URL in the transfer info"
)
self._client.log(
logging.DEBUG,
f"Downloading file from {download_url} "
f"to {file_name}"
)
async with self._client._session.stream(
"GET",
download_url
) as resp:
resp.raise_for_status()
async with aiofiles.open(file_name, "wb") as f:
async for chunk in resp.aiter_bytes(
chunk_size=self.chunk_size
):
await f.write(chunk)
self._client.log(
logging.DEBUG,
f"Downloaded file from {download_url} to {file_name}"
)
async def download_file_streamer(self, file_path=None):
file_name = file_path or self._file_path
coordinates = self._transfer_info.get(
"transferDirectives", {}
).get("coordinates")
if coordinates is None:
raise MultipartUploadException(
self._transfer_info,
"Could not find download coordinates in the transfer info"
)
self._client.log(
logging.DEBUG,
f"Downloading file {file_name} with `{coordinates}` "
f"coordinates"
)
config = cli.set_coordinates(coordinates)
config.target = file_name
await cli.client_receive(config)
self._client.log(
logging.DEBUG,
f"Downloaded file {file_name} from {coordinates} "
f"using Streamer client"
)
class AsyncFirecrest:
"""
This is the basic class you instantiate to access the FirecREST API v2.
Necessary parameters are the firecrest URL and an authorization object.
:param firecrest_url: FirecREST's URL
:param authorization: the authorization object. This object is responsible
of handling the credentials and the only requirement
for it is that it has a method get_access_token()
that returns a valid access token.
:param verify: either a boolean, in which case it controls whether
requests will verify the server’s TLS certificate,
or a string, in which case it must be a path to a CA bundle
to use
"""
TOO_MANY_REQUESTS_CODE = 429
MAX_DIRECT_UPLOAD_SIZE = 1048576
MAX_S3_CONNECTIONS = 10
def _retry_requests(func):
async def wrapper(*args, **kwargs):
client = args[0]
num_retries = 0
resp = await func(*args, **kwargs)
while True:
if resp.status_code != client.TOO_MANY_REQUESTS_CODE:
break
elif (
client.num_retries_rate_limit is not None
and num_retries >= client.num_retries_rate_limit
):
client.log(
logging.DEBUG,
f"Rate limit is reached and the request has "
f"been retried already {num_retries} times"
)
break
else:
reset = resp.headers.get(
"Retry-After",
default=resp.headers.get(
"RateLimit-Reset", default=10
),
)
reset = parse_retry_after(reset, client.log)
client.log(
logging.INFO,
f"Rate limit is reached, will sleep for "
f"{reset} seconds and try again"
)
await asyncio.sleep(reset)
resp = await func(*args, **kwargs)
num_retries += 1
return resp
return wrapper
def __init__(
self,
firecrest_url: str,
authorization: Any,
verify: str | bool | ssl.SSLContext = True,
) -> None:
self._firecrest_url = firecrest_url.rstrip('/')
self._authorization = authorization
self._verify = verify
#: This attribute will be passed to all the requests that will be made.
#: How many seconds to wait for the server to send data before giving
# up. After that time a `requests.exceptions.Timeout` error will be
# raised.
#:
#: It can be a float or a tuple. More details here:
# https://www.python-httpx.org/advanced/#fine-tuning-the-configuration.
self.timeout: Any = None
# type is Any because of some incompatibility between httpx and
# requests library
#: Disable all logging from the client.
self.disable_client_logging: bool = False
#: Number of retries in case the rate limit is reached. When it is set
# to `None`, the client will keep trying until it gets a different
# status code than 429.
self.num_retries_rate_limit: Optional[int] = None
self._api_version: Version = parse("2.4.0")
self._session = httpx.AsyncClient(verify=self._verify)
self._upload_semaphore = asyncio.Semaphore(self.MAX_S3_CONNECTIONS)
def set_api_version(self, api_version: str) -> None:
"""Set the version of the api of firecrest. By default it will be
assumed that you are using version 2.4.0 or compatible. The version is
parsed by the `packaging` library.
"""
self._api_version = parse(api_version)
async def close_session(self) -> None:
"""Close the httpx session"""
await self._session.aclose()
async def create_new_session(self) -> None:
"""Create a new httpx session"""
if not self._session.is_closed:
await self._session.aclose()
self._session = httpx.AsyncClient(verify=self._verify)
def set_maximum_s3_connections(self, max_connections: int) -> None:
"""Set the maximum number of simultaneous connections to S3. By
default it is set to 10.
"""
# TODO: Check if the semaphore is used?
self._upload_semaphore = asyncio.Semaphore(max_connections)
@property
def is_session_closed(self) -> bool:
"""Check if the httpx session is closed"""
return self._session.is_closed
def log(self, level: int, msg: Any) -> None:
"""Log a message with the given level on the client logger.
"""
if not self.disable_client_logging:
logger.log(level, msg)
@_retry_requests # type: ignore
async def _get_request(
self,
endpoint,
additional_headers=None,
params=None
) -> httpx.Response:
url = f"{self._firecrest_url}{endpoint}"
headers = {
"Authorization": f"Bearer {self._authorization.get_access_token()}"
}
if additional_headers:
headers.update(additional_headers)
self.log(logging.DEBUG, f"Making GET request to {endpoint}")
with time_block(f"GET request to {endpoint}", logger):
resp = await self._session.get(
url=url, headers=headers, params=params, timeout=self.timeout
)
return resp
@_retry_requests # type: ignore
async def _post_request(
self, endpoint, additional_headers=None, params=None, data=None, files=None
) -> httpx.Response:
url = f"{self._firecrest_url}{endpoint}"
headers = {
"Authorization": f"Bearer {self._authorization.get_access_token()}"
}
if additional_headers:
headers.update(additional_headers)
self.log(logging.DEBUG, f"Making POST request to {endpoint}")
with time_block(f"POST request to {endpoint}", logger):
resp = await self._session.post(
url=url,
headers=headers,
params=params,
data=data,
files=files,
timeout=self.timeout
)
return resp
@_retry_requests # type: ignore
async def _put_request(
self, endpoint, additional_headers=None, data=None
) -> httpx.Response:
url = f"{self._firecrest_url}{endpoint}"
headers = {
"Authorization": f"Bearer {self._authorization.get_access_token()}"
}
if additional_headers:
headers.update(additional_headers)
self.log(logging.DEBUG, f"Making PUT request to {endpoint}")
with time_block(f"PUT request to {endpoint}", logger):
resp = await self._session.put(
url=url, headers=headers, data=data, timeout=self.timeout
)
return resp
@_retry_requests # type: ignore
async def _delete_request(
self, endpoint, additional_headers=None, params=None, data=None
) -> httpx.Response:
url = f"{self._firecrest_url}{endpoint}"
headers = {
"Authorization": f"Bearer {self._authorization.get_access_token()}"
}
if additional_headers:
headers.update(additional_headers)
self.log(logging.INFO, f"Making DELETE request to {endpoint}")
with time_block(f"DELETE request to {endpoint}", logger):
# httpx doesn't support data in the `delete` method so we will
# have to use the generic `request` method
# https://www.python-httpx.org/compatibility/#request-body-on-http-methods
resp = await self._session.request(
method="DELETE",
url=url,
headers=headers,
params=params,
data=data,
timeout=self.timeout,
)
return resp
def _check_response(
self,
response: httpx.Response,
expected_status_code: int,
return_json: bool = True
) -> dict:
status_code = response.status_code
# handle_response(response)
if status_code != expected_status_code:
self.log(
logging.DEBUG,
f"Unexpected status of last request {status_code}, it "
f"should have been {expected_status_code}"
)
raise UnexpectedStatusException(
[response], expected_status_code
)
return response.json() if return_json and status_code != 204 else {}
async def server_version(self) -> str | None:
"""Returns the exact API version of the FirecREST server.
:calls: GET `/status/systems`
"""
resp = await self._get_request(endpoint="/status/systems")
if resp.headers.get("f7t-appversion") == "2.x.x":
return "2"
elif (
resp.headers.get("f7t-appversion")
):
return resp.headers["f7t-appversion"]
else:
return None
async def systems(self) -> List[dict]:
"""Returns available systems.
:calls: GET `/status/systems`
"""
resp = await self._get_request(endpoint="/status/systems")
return self._check_response(resp, 200)['systems']
async def nodes(
self,
system_name: str
) -> List[dict]:
"""Returns nodes of the system.
:param system_name: the system name where the nodes belong to
:calls: GET `/status/{system_name}/nodes`
"""
resp = await self._get_request(
endpoint=f"/status/{system_name}/nodes"
)
return self._check_response(resp, 200)['nodes']
async def reservations(
self,
system_name: str
) -> List[dict]:
"""Returns reservations defined in the system.
:param system_name: the system name where the reservations belong to
:calls: GET `/status/{system_name}/reservations`
"""
resp = await self._get_request(
endpoint=f"/status/{system_name}/reservations"
)
return self._check_response(resp, 200)['reservations']
async def partitions(
self,
system_name: str
) -> List[dict]:
"""Returns partitions defined in the scheduler of the system.
:param system_name: the system name where the partitions belong to
:calls: GET `/status/{system_name}/partitions`
"""
resp = await self._get_request(
endpoint=f"/status/{system_name}/partitions"
)
return self._check_response(resp, 200)["partitions"]
async def userinfo(
self,
system_name: str
) -> dict:
"""Returns user and groups information.
:calls: GET `/status/{system_name}/userinfo`
"""
resp = await self._get_request(
endpoint=f"/status/{system_name}/userinfo"
)
return self._check_response(resp, 200)
async def list_files(
self,
system_name: str,
path: str,
show_hidden: bool = False,
recursive: bool = False,
numeric_uid: bool = False,
dereference: bool = False
) -> List[dict]:
"""Returns a list of files in a directory.
:param system_name: the system name where the filesystem belongs to
:param path: the absolute target path
:param show_hidden: Show hidden files
:param recursive: recursively list directories encountered
:numeric_uid: list numeric user and group IDs
:param dereference: when showing file information for a symbolic link,
show information for the file the link references
rather than for the link itself
:calls: GET `/filesystem/{system_name}/ops/ls`
"""
resp = await self._get_request(
endpoint=f"/filesystem/{system_name}/ops/ls",
params={
"path": path,
"showHidden": show_hidden,
"recursive": recursive,
"numericUid": numeric_uid,
"dereference": dereference
}
)
return self._check_response(resp, 200)["output"]
async def head(
self,
system_name: str,
path: str,
num_bytes: Optional[int] = None,
num_lines: Optional[int] = None,
exclude_trailing: bool = False,
) -> dict:
"""Display the beginning of a specified file.
By default 10 lines will be returned.
`num_bytes` and `num_lines` cannot be specified simultaneously.
:param system_name: the system name where the filesystem belongs to
:param path: the absolute target path of the file
:param num_bytes: the output will be the first NUM bytes of each file
:param num_lines: the output will be the first NUM lines of each file
:param exclude_trailing: the output will be the whole file, without
the last NUM bytes/lines of each file. NUM
should be specified in the respective
argument through ``bytes`` or ``lines``.
:calls: GET `/filesystem/{system_name}/ops/head`
"""
# Validate that num_bytes and num_lines are not passed together
if num_bytes is not None and num_lines is not None:
raise ValueError(
"You cannot specify both `num_bytes` and `num_lines`."
)
# If `exclude_trailing` is passed, either `num_bytes` or `num_lines`
# must be passed
if exclude_trailing and num_bytes is None and num_lines is None:
raise ValueError(
"`exclude_trailing` requires either `num_bytes` or "
"`num_lines` to be specified.")
params = {
"path": path,
"skipTrailing": exclude_trailing
}
if num_bytes is not None:
params["bytes"] = num_bytes
if num_lines is not None:
params["lines"] = num_lines
resp = await self._get_request(
endpoint=f"/filesystem/{system_name}/ops/head",
params=params
)
return self._check_response(resp, 200)['output']
async def tail(
self,
system_name: str,
path: str,
num_bytes: Optional[int] = None,
num_lines: Optional[int] = None,
exclude_beginning: bool = False,
) -> dict:
"""Display the ending of a specified file.
By default, 10 lines will be returned.
`num_bytes` and `num_lines` cannot be specified simultaneously.
:param system_name: the system name where the filesystem belongs to
:param path: the absolute target path of the file
:param num_bytes: The output will be the last NUM bytes of each file
:param num_lines: The output will be the last NUM lines of each file
:param exclude_beginning: The output will be the whole file, without
the first NUM bytes/lines of each file. NUM
should be specified in the respective
argument through ``num_bytes`` or
``num_lines``.
:calls: GET `/filesystem/{system_name}/ops/tail`
"""
# Ensure `num_bytes` and `num_lines` are not passed together
if num_bytes is not None and num_lines is not None:
raise ValueError(
"You cannot specify both `num_bytes` and `num_lines`."
)
# If `exclude_beginning` is passed, either `num_bytes` or `num_lines`
# must be passed
if exclude_beginning and num_bytes is None and num_lines is None:
raise ValueError(
"`exclude_beginning` requires either `num_bytes` or "
"`num_lines` to be specified."
)
params = {
"path": path,
"skipHeading": exclude_beginning
}
if num_bytes is not None:
params["bytes"] = num_bytes
if num_lines is not None:
params["lines"] = num_lines
resp = await self._get_request(
endpoint=f"/filesystem/{system_name}/ops/tail",
params=params
)
return self._check_response(resp, 200)['output']
async def view(
self,
system_name: str,
path: str,
) -> str:
"""
View full file content (up to 5MB files)
:param system_name: the system name where the filesystem belongs to
:param path: the absolute target path of the file
:calls: GET `/filesystem/{system_name}/ops/view`
"""
resp = await self._get_request(
endpoint=f"/filesystem/{system_name}/ops/view",
params={"path": path}
)
return self._check_response(resp, 200)["output"]
async def checksum(
self,
system_name: str,
path: str,
) -> dict:
"""
Calculate the SHA256 (256-bit) checksum of a specified file.
:param system_name: the system name where the filesystem belongs to
:param path: the absolute target path of the file
:calls: GET `/filesystem/{system_name}/ops/checksum`
"""
resp = await self._get_request(
endpoint=f"/filesystem/{system_name}/ops/checksum",
params={"path": path}
)
return self._check_response(resp, 200)["output"]
async def file_type(
self,
system_name: str,
path: str,
) -> str:
"""
Uses the `file` linux application to determine the type of a file.
:param system_name: the system name where the filesystem belongs to
:param path: the absolute target path of the file
:calls: GET `/filesystem/{system_name}/ops/file`
"""
resp = await self._get_request(
endpoint=f"/filesystem/{system_name}/ops/file",
params={"path": path}
)
return self._check_response(resp, 200)["output"]
async def chmod(
self,
system_name: str,
path: str,
mode: str
) -> dict:
"""Changes the file mod bits of a given file according to the
specified mode.
:param system_name: the system name where the filesystem belongs to
:param path: the absolute target path of the file
:param mode: same as numeric mode of linux chmod tool
:calls: PUT `/filesystem/{system_name}/ops/chmod`
"""
data: dict[str, str] = {
"path": path,
"mode": mode
}
resp = await self._put_request(
endpoint=f"/filesystem/{system_name}/ops/chmod",
data=json.dumps(data)
)
return self._check_response(resp, 200)["output"]
async def chown(
self,
system_name: str,
path: str,
owner: str,
group: str
) -> dict:
"""Changes the user and/or group ownership of a given file.
If only owner or group information is passed, only that information
will be updated.
:param system_name: the system name where the filesystem belongs to
:param path: the absolute target path of the file
:param owner: owner ID for target
:param group: group ID for target
:calls: PUT `/filesystem/{system_name}/ops/chown`
"""
data: dict[str, str] = {
"path": path,
"owner": owner,
"group": group
}
resp = await self._put_request(
endpoint=f"/filesystem/{system_name}/ops/chown",
data=json.dumps(data)
)
return self._check_response(resp, 200)["output"]
async def stat(
self,
system_name: str,
path: str,
dereference: bool = False,
) -> dict:
"""
Uses the stat linux application to determine the status of a file on
the system's filesystem. The result follows:
https://docs.python.org/3/library/os.html#os.stat_result.
:param system_name: the system name where the filesystem belongs to
:param path: the absolute target path
:param dereference: follow symbolic links
:calls: GET `/filesystem/{system_name}/ops/stat`
"""
resp = await self._get_request(
endpoint=f"/filesystem/{system_name}/ops/stat",
params={
"path": path,
"dereference": dereference
}
)
return self._check_response(resp, 200)["output"]
async def symlink(
self,
system_name: str,
source_path: str,
link_path: str,
) -> dict:
"""Create a symbolic link.
:param system_name: the system name where the filesystem belongs to
:param source_path: the absolute path to the file the link points to
:param link_path: the absolute path to the symlink
:calls: POST `/filesystem/{system_name}/ops/symlink`
"""
resp = await self._post_request(
endpoint=f"/filesystem/{system_name}/ops/symlink",
data=json.dumps({
"sourcePath": source_path,
"linkPath": link_path
})
)
return self._check_response(resp, 201)
async def mkdir(
self,
system_name: str,
path: str,
create_parents: bool = False
) -> dict:
"""Create a directory.
:param system_name: the system name where the filesystem belongs to
:param path: the absolute path to the new directory
:param create_parents: create intermediate parent directories
:calls: POST `/filesystem/{system_name}/ops/mkdir`
"""
resp = await self._post_request(
endpoint=f"/filesystem/{system_name}/ops/mkdir",
data=json.dumps({
"sourcePath": path,
"parent": create_parents
})
)
return self._check_response(resp, 201)["output"]
async def mv(
self,