-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcore_api.py
More file actions
1100 lines (948 loc) · 34.9 KB
/
core_api.py
File metadata and controls
1100 lines (948 loc) · 34.9 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
import asyncio
import io
import logging
import pprint
from typing import Optional
import pydantic
from bluesky_queueserver.manager.conversions import simplify_plan_descriptions, spreadsheet_to_plan_list
from fastapi import APIRouter, Depends, File, Form, Request, Security, UploadFile
from packaging import version
if version.parse(pydantic.__version__) < version.parse("2.0.0"):
from pydantic import BaseSettings
else:
from pydantic_settings import BaseSettings
from ..authentication import get_current_principal
from ..console_output import ConsoleOutputEventStream, StreamingResponseFromClass
from ..resources import SERVER_RESOURCES as SR
from ..settings import get_settings
from ..utils import (
get_api_access_manager,
get_current_username,
get_resource_access_manager,
process_exception,
validate_payload_keys,
)
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api")
@router.get("/")
@router.get("/ping")
async def ping_handler(payload: dict = {}, principal=Security(get_current_principal, scopes=["read:status"])):
"""
May be called to get some response from the server. Currently returns status of RE Manager.
"""
try:
msg = await SR.RM.ping(**payload)
except Exception:
process_exception()
return msg
@router.get("/status")
async def status_handler(
request: Request,
payload: dict = {},
principal=Security(get_current_principal, scopes=["read:status"]),
):
"""
Returns status of RE Manager.
"""
request.state.endpoint = "status"
# logger.info(f"payload = {payload} principal={principal}")
try:
msg = await SR.RM.status(**payload)
except Exception:
process_exception()
return msg
@router.get("/config/get")
async def queue_config_get(
payload: dict = {},
principal=Security(get_current_principal, scopes=["read:config"]),
):
"""
Get manager configuration.
"""
try:
msg = await SR.RM.config_get(**payload)
except Exception:
process_exception()
return msg
@router.post("/queue/autostart")
async def queue_autostart_handler(
payload: dict,
principal=Security(get_current_principal, scopes=["write:queue:control"]),
):
"""
Set queue mode.
"""
try:
msg = await SR.RM.queue_autostart(**payload)
except Exception:
process_exception()
return msg
@router.post("/queue/mode/set")
async def queue_mode_set_handler(
payload: dict,
principal=Security(get_current_principal, scopes=["write:queue:control"]),
):
"""
Set queue mode.
"""
try:
msg = await SR.RM.queue_mode_set(**payload)
except Exception:
process_exception()
return msg
@router.get("/queue/get")
async def queue_get_handler(payload: dict = {}, principal=Security(get_current_principal, scopes=["read:queue"])):
"""
Returns the contents of the current queue.
"""
try:
msg = await SR.RM.queue_get(**payload)
except Exception:
process_exception()
return msg
@router.post("/queue/clear")
async def queue_clear_handler(
payload: dict = {}, principal=Security(get_current_principal, scopes=["write:queue:edit"])
):
"""
Clear the plan queue.
"""
try:
msg = await SR.RM.queue_clear(**payload)
except Exception:
process_exception()
return msg
@router.post("/queue/start")
async def queue_start_handler(
payload: dict = {}, principal=Security(get_current_principal, scopes=["write:queue:control"])
):
"""
Start execution of the loaded queue. Additional runs can be added to the queue while
it is executed. If the queue is empty, then nothing will happen.
"""
try:
msg = await SR.RM.queue_start(**payload)
except Exception:
process_exception()
return msg
@router.post("/queue/stop")
async def queue_stop(
payload: dict = {}, principal=Security(get_current_principal, scopes=["write:queue:control"])
):
"""
Activate the sequence of stopping the queue. The currently running plan will be completed,
but the next plan will not be started. The request will be rejected if no plans are currently
running
"""
try:
msg = await SR.RM.queue_stop(**payload)
except Exception:
process_exception()
return msg
@router.post("/queue/stop/cancel")
async def queue_stop_cancel(
payload: dict = {}, principal=Security(get_current_principal, scopes=["write:queue:control"])
):
"""
Cancel pending request to stop the queue while the current plan is still running.
It may be useful if the `/queue/stop` request was issued by mistake or the operator
changed his mind. Since `/queue/stop` takes effect only after the currently running
plan is completed, user may have time to cancel the request and continue execution of
the queue. The command always succeeds, but it has no effect if no queue stop
requests are pending.
"""
try:
msg = await SR.RM.queue_stop_cancel(**payload)
except Exception:
process_exception()
return msg
@router.post("/queue/item/add")
async def queue_item_add_handler(
payload: dict = {},
principal=Security(get_current_principal, scopes=["write:queue:edit"]),
settings: BaseSettings = Depends(get_settings),
api_access_manager=Depends(get_api_access_manager),
resource_access_manager=Depends(get_resource_access_manager),
):
"""
Adds new plan to the queue
"""
try:
username = get_current_username(
principal=principal, settings=settings, api_access_manager=api_access_manager
)[0]
displayed_name = api_access_manager.get_displayed_user_name(username)
user_group = resource_access_manager.get_resource_group(username, principal.roles)
payload.update({"user": displayed_name, "user_group": user_group})
if "item" not in payload:
# We can not use API, so let the server handle the parameters
msg = await SR.RM.send_request(method="queue_item_add", params=payload)
else:
msg = await SR.RM.item_add(**payload)
except Exception:
process_exception()
return msg
@router.post("/queue/item/execute")
async def queue_item_execute_handler(
payload: dict,
principal=Security(get_current_principal, scopes=["write:execute"]),
settings: BaseSettings = Depends(get_settings),
api_access_manager=Depends(get_api_access_manager),
resource_access_manager=Depends(get_resource_access_manager),
):
"""
Immediately execute an item
"""
try:
username = get_current_username(
principal=principal, settings=settings, api_access_manager=api_access_manager
)[0]
displayed_name = api_access_manager.get_displayed_user_name(username)
user_group = resource_access_manager.get_resource_group(username, principal.roles)
payload.update({"user": displayed_name, "user_group": user_group})
if "item" not in payload:
# We can not use API, so let the server handle the parameters
msg = await SR.RM.send_request(method="queue_item_execute", params=payload)
else:
msg = await SR.RM.item_execute(**payload)
except Exception:
process_exception()
return msg
@router.post("/queue/item/add/batch")
async def queue_item_add_batch_handler(
payload: dict,
principal=Security(get_current_principal, scopes=["write:queue:edit"]),
settings: BaseSettings = Depends(get_settings),
api_access_manager=Depends(get_api_access_manager),
resource_access_manager=Depends(get_resource_access_manager),
):
"""
Adds new plan to the queue
"""
try:
username = get_current_username(
principal=principal, settings=settings, api_access_manager=api_access_manager
)[0]
displayed_name = api_access_manager.get_displayed_user_name(username)
user_group = resource_access_manager.get_resource_group(username, principal.roles)
payload.update({"user": displayed_name, "user_group": user_group})
if "items" not in payload:
# We can not use API, so let the server handle the parameters
msg = await SR.RM.send_request(method="queue_item_add_batch", params=payload)
else:
msg = await SR.RM.item_add_batch(**payload)
except Exception:
process_exception()
return msg
@router.post("/queue/upload/spreadsheet")
async def queue_upload_spreadsheet(
spreadsheet: UploadFile = File(...),
data_type: Optional[str] = Form(None),
principal=Security(get_current_principal, scopes=["write:queue:edit"]),
settings: BaseSettings = Depends(get_settings),
api_access_manager=Depends(get_api_access_manager),
resource_access_manager=Depends(get_resource_access_manager),
):
"""
The endpoint receives uploaded spreadsheet, converts it to the list of plans and adds
the plans to the queue.
Parameters
----------
spreadsheet : File
uploaded excel file
data_type : str
user defined spreadsheet type, which determines which processing function is used to
process the spreadsheet.
Returns
-------
success : boolean
Indicates if the spreadsheet was successfully converted to a sequence of plans.
``True`` value does not indicate that the plans were accepted by the RE Manager and
successfully added to the queue.
msg : str
Error message in case of failure to process the spreadsheet
item_list : list(dict)
The list of parameter dictionaries returned by RE Manager in response to requests
to add each plan in the list. Check ``success`` parameter in each dictionary to
see if the plan was accepted and ``msg`` parameter for an error message in case
the plan was rejected. The list may be empty if the spreadsheet contains no items
or processing of the spreadsheet failed.
"""
try:
# Create fully functional file object. The file object returned by FastAPI is not fully functional.
f = io.BytesIO(spreadsheet.file.read())
# File name is also passed to the processing function (may be useful in user created
# processing code, since processing may differ based on extension or file name)
f_name = spreadsheet.filename
logger.info(f"Spreadsheet file '{f_name}' was uploaded")
# Determine which processing function should be used
item_list = []
processed = False
# Select custom module from the list of loaded modules
custom_module = None
for module in SR.custom_code_modules:
if "spreadsheet_to_plan_list" in module.__dict__:
custom_module = module
break
username = get_current_username(
principal=principal, settings=settings, api_access_manager=api_access_manager
)[0]
displayed_name = api_access_manager.get_displayed_user_name(username)
user_group = resource_access_manager.get_resource_group(username, principal.roles)
if custom_module:
logger.info("Processing spreadsheet using function from external module ...")
# Try applying the custom processing function. Some additional useful data is passed to
# the function. Unnecessary parameters can be ignored.
item_list = custom_module.spreadsheet_to_plan_list(
spreadsheet_file=f, file_name=f_name, data_type=data_type, user=username
)
# The function is expected to return None if it rejects the file (based on 'data_type').
# Then try to apply the default processing function.
processed = item_list is not None
if not processed:
# Apply default spreadsheet processing function.
logger.info("Processing spreadsheet using default function ...")
item_list = spreadsheet_to_plan_list(
spreadsheet_file=f, file_name=f_name, data_type=data_type, user=username
)
if item_list is None:
raise RuntimeError("Failed to process the spreadsheet: unsupported data type or format")
# Since 'item_list' may be returned by user defined functions, verify the type of the list.
if not isinstance(item_list, (tuple, list)):
raise ValueError(
f"Spreadsheet processing function returned value of '{type(item_list)}' "
f"type instead of 'list' or 'tuple'"
)
# Ensure, that 'item_list' is sent as a list
item_list = list(item_list)
# Set item type for all items that don't have item type already set (item list may contain
# instructions, but it is responsibility of the user to set item types correctly.
# By default an item is considered a plan.
for item in item_list:
if "item_type" not in item:
item["item_type"] = "plan"
logger.debug("The following plans were created: %s", pprint.pformat(item_list))
except Exception as ex:
msg = {"success": False, "msg": str(ex), "items": [], "results": []}
else:
try:
params = {"user": displayed_name, "user_group": user_group}
params["items"] = item_list
msg = await SR.RM.item_add_batch(**params)
except Exception:
process_exception()
return msg
@router.post("/queue/item/update")
async def queue_item_update_handler(
payload: dict,
principal=Security(get_current_principal, scopes=["write:queue:edit"]),
settings: BaseSettings = Depends(get_settings),
api_access_manager=Depends(get_api_access_manager),
resource_access_manager=Depends(get_resource_access_manager),
):
"""
Update existing plan in the queue
"""
try:
username = get_current_username(
principal=principal, settings=settings, api_access_manager=api_access_manager
)[0]
displayed_name = api_access_manager.get_displayed_user_name(username)
user_group = resource_access_manager.get_resource_group(username, principal.roles)
payload.update({"user": displayed_name, "user_group": user_group})
msg = await SR.RM.item_update(**payload)
except Exception:
process_exception()
return msg
@router.post("/queue/item/remove")
async def queue_item_remove_handler(
payload: dict,
principal=Security(get_current_principal, scopes=["write:queue:edit"]),
):
"""
Remove plan from the queue
"""
try:
msg = await SR.RM.item_remove(**payload)
except Exception:
process_exception()
return msg
@router.post("/queue/item/remove/batch")
async def queue_item_remove_batch_handler(
payload: dict,
principal=Security(get_current_principal, scopes=["write:queue:edit"]),
):
"""
Remove a batch of plans from the queue
"""
try:
if "uids" not in payload:
# We can not use API, so let the server handle the parameters
msg = await SR.RM.send_request(method="queue_item_remove_batch", params=payload)
else:
msg = await SR.RM.item_remove_batch(**payload)
except Exception:
process_exception()
return msg
@router.post("/queue/item/move")
async def queue_item_move_handler(
payload: dict,
principal=Security(get_current_principal, scopes=["write:queue:edit"]),
):
"""
Move plan in the queue
"""
try:
msg = await SR.RM.item_move(**payload)
except Exception:
process_exception()
return msg
@router.post("/queue/item/move/batch")
async def queue_item_move_batch_handler(
payload: dict,
principal=Security(get_current_principal, scopes=["write:queue:edit"]),
):
"""
Move a batch of plans in the queue
"""
try:
msg = await SR.RM.item_move_batch(**payload)
except Exception:
process_exception()
return msg
@router.get("/queue/item/get")
async def queue_item_get_handler(
payload: dict = {}, principal=Security(get_current_principal, scopes=["read:queue"])
):
"""
Get a plan from the queue
"""
try:
msg = await SR.RM.item_get(**payload)
except Exception:
process_exception()
return msg
@router.get("/history/get")
async def history_get_handler(
payload: dict = {}, principal=Security(get_current_principal, scopes=["read:history"])
):
"""
Returns the plan history (list of dicts).
"""
try:
msg = await SR.RM.history_get(**payload)
except Exception:
process_exception()
return msg
@router.post("/history/clear")
async def history_clear_handler(
payload: dict = {}, principal=Security(get_current_principal, scopes=["write:history:edit"])
):
"""
Clear plan history.
"""
try:
msg = await SR.RM.history_clear(**payload)
except Exception:
process_exception()
return msg
@router.post("/environment/open")
async def environment_open_handler(
payload: dict = {}, principal=Security(get_current_principal, scopes=["write:manager:control"])
):
"""
Creates RE environment: creates RE Worker process, starts and configures Run Engine.
"""
try:
msg = await SR.RM.environment_open(**payload)
except Exception:
process_exception()
return msg
@router.post("/environment/close")
async def environment_close_handler(
payload: dict = {}, principal=Security(get_current_principal, scopes=["write:manager:control"])
):
"""
Orderly closes of RE environment. The command returns success only if no plan is running,
i.e. RE Manager is in the idle state. The command is rejected if a plan is running.
"""
try:
msg = await SR.RM.environment_close(**payload)
except Exception:
process_exception()
return msg
@router.post("/environment/destroy")
async def environment_destroy_handler(
payload: dict = {}, principal=Security(get_current_principal, scopes=["write:manager:control"])
):
"""
Destroys RE environment by killing RE Worker process. This is a last resort command which
should be made available only to expert level users.
"""
try:
msg = await SR.RM.environment_destroy(**payload)
except Exception:
process_exception()
return msg
@router.post("/environment/update")
async def environment_update_handler(
payload: dict = {}, principal=Security(get_current_principal, scopes=["write:queue:control"])
):
"""
Updates RE environment cache.
"""
try:
msg = await SR.RM.environment_update(**payload)
except Exception:
process_exception()
return msg
@router.post("/re/pause")
async def re_pause_handler(
payload: dict = {},
principal=Security(get_current_principal, scopes=["write:plan:control"]),
):
"""
Pause Run Engine.
"""
try:
msg = await SR.RM.re_pause(**payload)
except Exception:
process_exception()
return msg
@router.post("/re/resume")
async def re_resume_handler(
payload: dict = {}, principal=Security(get_current_principal, scopes=["write:plan:control"])
):
"""
Run Engine: resume execution of a paused plan
"""
try:
msg = await SR.RM.re_resume(**payload)
except Exception:
process_exception()
return msg
@router.post("/re/stop")
async def re_stop_handler(
payload: dict = {}, principal=Security(get_current_principal, scopes=["write:plan:control"])
):
"""
Run Engine: stop execution of a paused plan
"""
try:
msg = await SR.RM.re_stop(**payload)
except Exception:
process_exception()
return msg
@router.post("/re/abort")
async def re_abort_handler(
payload: dict = {}, principal=Security(get_current_principal, scopes=["write:plan:control"])
):
"""
Run Engine: abort execution of a paused plan
"""
try:
msg = await SR.RM.re_abort(**payload)
except Exception:
process_exception()
return msg
@router.post("/re/halt")
async def re_halt_handler(
payload: dict = {}, principal=Security(get_current_principal, scopes=["write:plan:control"])
):
"""
Run Engine: halt execution of a paused plan
"""
try:
msg = await SR.RM.re_halt(**payload)
except Exception:
process_exception()
return msg
@router.post("/re/runs")
async def re_runs_handler(payload: dict = {}, principal=Security(get_current_principal, scopes=["read:monitor"])):
"""
Run Engine: download the list of active, open or closed runs (runs that were opened
during execution of the currently running plan and combines the subsets of 'open' and
'closed' runs.) The parameter ``options`` is used to select the category of runs
(``'active'``, ``'open'`` or ``'closed'``). By default the API returns the active runs.
"""
try:
msg = await SR.RM.re_runs(**payload)
except Exception:
process_exception()
return msg
@router.get("/re/runs/active")
async def re_runs_active_handler(principal=Security(get_current_principal, scopes=["read:monitor"])):
"""
Run Engine: download the list of active runs (runs that were opened during execution of
the currently running plan and combines the subsets of 'open' and 'closed' runs.)
"""
try:
params = {"option": "active"}
msg = await SR.RM.re_runs(**params)
except Exception:
process_exception()
return msg
@router.get("/re/runs/open")
async def re_runs_open_handler(principal=Security(get_current_principal, scopes=["read:monitor"])):
"""
Run Engine: download the subset of active runs that includes runs that were open, but not yet closed.
"""
try:
params = {"option": "open"}
msg = await SR.RM.re_runs(**params)
except Exception:
process_exception()
return msg
@router.get("/re/runs/closed")
async def re_runs_closed_handler(principal=Security(get_current_principal, scopes=["read:monitor"])):
"""
Run Engine: download the subset of active runs that includes runs that were already closed.
"""
try:
params = {"option": "closed"}
msg = await SR.RM.re_runs(**params)
except Exception:
process_exception()
return msg
@router.get("/plans/allowed")
async def plans_allowed_handler(
payload: dict = {},
principal=Security(get_current_principal, scopes=["read:resources"]),
settings: BaseSettings = Depends(get_settings),
api_access_manager=Depends(get_api_access_manager),
resource_access_manager=Depends(get_resource_access_manager),
):
"""
Returns the lists of allowed plans. If boolean optional parameter ``reduced``
is ``True``(default value is ``False`), then simplify plan descriptions before
calling the API.
"""
try:
validate_payload_keys(payload, optional_keys=["reduced"])
username = get_current_username(
principal=principal, settings=settings, api_access_manager=api_access_manager
)[0]
user_group = resource_access_manager.get_resource_group(username, principal.roles)
if "reduced" in payload:
reduced = payload["reduced"]
del payload["reduced"]
else:
reduced = False
payload.update({"user_group": user_group})
msg = await SR.RM.plans_allowed(**payload)
if reduced and ("plans_allowed" in msg):
msg["plans_allowed"] = simplify_plan_descriptions(msg["plans_allowed"])
except Exception:
process_exception()
return msg
@router.get("/devices/allowed")
async def devices_allowed_handler(
payload: dict = {},
principal=Security(get_current_principal, scopes=["read:resources"]),
settings: BaseSettings = Depends(get_settings),
api_access_manager=Depends(get_api_access_manager),
resource_access_manager=Depends(get_resource_access_manager),
):
"""
Returns the lists of allowed devices.
"""
try:
username = get_current_username(
principal=principal, settings=settings, api_access_manager=api_access_manager
)[0]
user_group = resource_access_manager.get_resource_group(username, principal.roles)
payload.update({"user_group": user_group})
msg = await SR.RM.devices_allowed(**payload)
except Exception:
process_exception()
return msg
@router.get("/plans/existing")
async def plans_existing_handler(
payload: dict = {},
):
"""
Returns the lists of existing plans. If boolean optional parameter ``reduced``
is ``True``(default value is ``False`), then simplify plan descriptions before
calling the API.
"""
try:
validate_payload_keys(payload, optional_keys=["reduced"])
if "reduced" in payload:
reduced = payload["reduced"]
del payload["reduced"]
else:
reduced = False
msg = await SR.RM.plans_existing(**payload)
if reduced and ("plans_existing" in msg):
msg["plans_existing"] = simplify_plan_descriptions(msg["plans_existing"])
except Exception:
process_exception()
return msg
@router.get("/devices/existing")
async def devices_existing_handler(
payload: dict = {},
principal=Security(get_current_principal, scopes=["read:resources"]),
):
"""
Returns the lists of existing devices.
"""
try:
msg = await SR.RM.devices_existing(**payload)
except Exception:
process_exception()
return msg
@router.post("/permissions/reload")
async def permissions_reload_handler(
payload: dict = {},
principal=Security(get_current_principal, scopes=["write:config"]),
):
"""
Reloads the list of allowed plans and devices and user group permission from the default location
or location set using command line parameters of RE Manager. Use this request to reload the data
if the respective files were changed on disk.
"""
try:
msg = await SR.RM.permissions_reload(**payload)
except Exception:
process_exception()
return msg
@router.get("/permissions/get")
async def permissions_get_handler(principal=Security(get_current_principal, scopes=["read:config"])):
"""
Download the dictionary of user group permissions.
"""
try:
msg = await SR.RM.permissions_get()
except Exception:
process_exception()
return msg
@router.post("/permissions/set")
async def permissions_set_handler(
payload: dict, principal=Security(get_current_principal, scopes=["write:permissions", "write:permissions"])
):
"""
Upload the dictionary of user group permissions (parameter: ``user_group_permissions``).
"""
try:
if "user_group_permissions" not in payload:
# We can not use API, so let the server handle the parameters
msg = await SR.RM.send_request(method="permissions_set", params=payload)
else:
msg = await SR.RM.permissions_set(**payload)
except Exception:
process_exception()
return msg
@router.post("/function/execute")
async def function_execute_handler(
payload: dict,
principal=Security(get_current_principal, scopes=["write:execute"]),
settings: BaseSettings = Depends(get_settings),
api_access_manager=Depends(get_api_access_manager),
resource_access_manager=Depends(get_resource_access_manager),
):
"""
Execute function defined in startup scripts in RE Worker environment.
"""
try:
username = get_current_username(
principal=principal, settings=settings, api_access_manager=api_access_manager
)[0]
displayed_name = api_access_manager.get_displayed_user_name(username)
user_group = resource_access_manager.get_resource_group(username, principal.roles)
payload.update({"user": displayed_name, "user_group": user_group})
if "item" not in payload:
# We can not use API, so let the server handle the parameters
msg = await SR.RM.send_request(method="function_execute", params=payload)
else:
msg = await SR.RM.function_execute(**payload)
except Exception:
process_exception()
return msg
@router.post("/script/upload")
async def script_upload_handler(
payload: dict, principal=Security(get_current_principal, scopes=["write:scripts"])
):
"""
Upload and execute script in RE Worker environment.
"""
try:
if "script" not in payload:
# We can not use API, so let the server handle the parameters
msg = await SR.RM.send_request(method="script_upload", params=payload)
else:
msg = await SR.RM.script_upload(**payload)
except Exception:
process_exception()
return msg
@router.get("/task/status")
async def task_status(payload: dict, principal=Security(get_current_principal, scopes=["read:monitor"])):
"""
Return status of one or more running tasks.
"""
try:
if "task_uid" not in payload:
# We can not use API, so let the server handle the parameters
msg = await SR.RM.send_request(method="task_status", params=payload)
else:
msg = await SR.RM.task_status(**payload)
except Exception:
process_exception()
return msg
@router.get("/task/result")
async def task_result(payload: dict, principal=Security(get_current_principal, scopes=["read:monitor"])):
"""
Return result of execution of a running or completed task.
"""
try:
if "task_uid" not in payload:
# We can not use API, so let the server handle the parameters
msg = await SR.RM.send_request(method="task_result", params=payload)
else:
msg = await SR.RM.task_result(**payload)
except Exception:
process_exception()
return msg
@router.post("/kernel/interrupt")
async def kernel_interrupt_handler(
payload: dict = {}, principal=Security(get_current_principal, scopes=["write:queue:control"])
):
"""
Interrupt IPython kernel.
"""
try:
msg = await SR.RM.kernel_interrupt(**payload)
except Exception:
process_exception()
return msg
@router.post("/lock")
async def lock_handler(
payload: dict,
principal=Security(get_current_principal, scopes=["write:lock"]),
settings: BaseSettings = Depends(get_settings),
api_access_manager=Depends(get_api_access_manager),
):
"""
Lock RE Manager.
"""
try:
username = get_current_username(
principal=principal, settings=settings, api_access_manager=api_access_manager
)[0]
displayed_name = api_access_manager.get_displayed_user_name(username)
payload.update({"user": displayed_name})
msg = await SR.RM.lock(**payload)
except Exception:
process_exception()
return msg
@router.post("/unlock")
async def unlock_handler(
payload: dict,
principal=Security(get_current_principal, scopes=["write:lock"]),
):
"""
Unlock RE Manager.
"""
try:
msg = await SR.RM.unlock(**payload)
except Exception:
process_exception()
return msg
@router.get("/lock/info")
async def lock_info_handler(
payload: dict,
principal=Security(get_current_principal, scopes=["read:lock"]),
):
"""
Unlock RE Manager.
"""
try:
msg = await SR.RM.lock_info(**payload)
except Exception:
process_exception()
return msg
@router.post("/manager/stop")
async def manager_stop_handler(