-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathcomputational_resources.py
1931 lines (1655 loc) · 69 KB
/
computational_resources.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
from __future__ import annotations
import copy
import enum
import re
import subprocess
import threading
from collections import namedtuple
from pathlib import Path
from uuid import UUID
import ipywidgets as ipw
import jinja2
import pexpect
import shortuuid
import traitlets as tl
from aiida import common, orm, plugins
from aiida.orm.utils.builders.computer import ComputerBuilder
from aiida.transports.plugins import ssh as aiida_ssh_plugin
from humanfriendly import InvalidSize, parse_size
from IPython.display import clear_output, display
from jinja2 import meta as jinja2_meta
from .databases import ComputationalResourcesDatabaseWidget
from .utils import MessageLevel, StatusHTML, wrap_message
STYLE = {"description_width": "180px"}
LAYOUT = {"width": "400px"}
class ComputationalResourcesWidget(ipw.VBox):
"""Code selection widget.
Attributes:
value(code UUID): Trait that points to the selected UUID of the code instance.
It can be set either to an AiiDA code UUID or to a code label.
It is linked to the `value` trait of the `self.code_select_dropdown` widget.
codes(Dict): Trait that contains a dictionary (label => Code UUID) for all
codes found in the AiiDA database for the selected plugin. It is linked
to the 'options' trait of the `self.code_select_dropdown` widget.
allow_hidden_codes(Bool): Trait that defines whether to show hidden codes or not.
allow_disabled_computers(Bool): Trait that defines whether to show codes on disabled
computers.
"""
value = tl.Unicode(allow_none=True)
codes = tl.Dict(allow_none=True)
allow_hidden_codes = tl.Bool(False)
allow_disabled_computers = tl.Bool(False)
# code output layout width
_output_width = "460px"
def __init__(
self,
description="Select code:",
enable_quick_setup=True,
enable_detailed_setup=True,
clear_after=None,
default_calc_job_plugin=None,
**kwargs,
):
"""Dropdown for Codes for one input plugin.
description (str): Description to display before the dropdown.
"""
clear_after = clear_after or 15
self.default_calc_job_plugin = default_calc_job_plugin
self.output = ipw.HTML()
self.setup_message = StatusHTML(clear_after=clear_after)
self.code_select_dropdown = ipw.Dropdown(
description=description,
disabled=True,
value=None,
style={"description_width": "initial"},
)
# Create bi-directional link between the code_select_dropdown and the codes trait.
tl.directional_link(
(self, "codes"),
(self.code_select_dropdown, "options"),
transform=lambda x: [(key, x[key]) for key in x],
)
tl.directional_link(
(self.code_select_dropdown, "options"),
(self, "codes"),
transform=lambda x: {c[0]: c[1] for c in x},
)
tl.link((self.code_select_dropdown, "value"), (self, "value"))
self.observe(
self.refresh, names=["allow_disabled_computers", "allow_hidden_codes"]
)
self.btn_setup_new_code = ipw.ToggleButton(description="Setup new code")
self.btn_setup_new_code.observe(self._setup_new_code, "value")
self._setup_new_code_output = ipw.Output(layout={"width": self._output_width})
children = [
ipw.HBox([self.code_select_dropdown, self.btn_setup_new_code]),
self._setup_new_code_output,
self.output,
]
super().__init__(children=children, **kwargs)
# Computer/code setup
self.resource_setup = _ResourceSetupBaseWidget(
default_calc_job_plugin=self.default_calc_job_plugin,
enable_quick_setup=enable_quick_setup,
enable_detailed_setup=enable_detailed_setup,
)
self.resource_setup.observe(self.refresh, "success")
tl.dlink(
(self.resource_setup, "message"),
(self.setup_message, "message"),
)
self.refresh()
def _get_codes(self):
"""Query the list of available codes."""
user = orm.User.collection.get_default()
filters = (
{"attributes.input_plugin": self.default_calc_job_plugin}
if self.default_calc_job_plugin
else {}
)
return [
(self._full_code_label(c[0]), c[0].uuid)
for c in orm.QueryBuilder()
.append(
orm.Code,
filters=filters,
)
.all()
if c[0].computer.is_user_configured(user)
and (self.allow_hidden_codes or not c[0].is_hidden)
and (self.allow_disabled_computers or c[0].computer.is_user_enabled(user))
]
@staticmethod
def _full_code_label(code):
return f"{code.label}@{code.computer.label}"
def refresh(self, _=None):
"""Refresh available codes.
The job of this function is to look in AiiDA database, find available codes and
put them in the code_select_dropdown widget."""
self.output.value = ""
with self.hold_trait_notifications():
self.code_select_dropdown.options = self._get_codes()
if not self.code_select_dropdown.options:
self.output.value = f"No codes found for default calcjob plugin {self.default_calc_job_plugin!r}."
self.code_select_dropdown.disabled = True
else:
self.code_select_dropdown.disabled = False
self.code_select_dropdown.value = None
@tl.validate("value")
def _validate_value(self, change):
"""Check if the code is valid in DB"""
code_uuid = change["value"]
self.output.value = ""
# If code None, set value to None.
if code_uuid is None:
return None
try:
_ = UUID(code_uuid, version=4)
except ValueError:
self.output.value = f"""'<span style="color:red">{code_uuid}</span>'
is not a valid UUID."""
else:
return code_uuid
def _setup_new_code(self, _=None):
with self._setup_new_code_output:
clear_output()
if self.btn_setup_new_code.value:
self._setup_new_code_output.layout = {
"width": self._output_width,
"border": "1px solid gray",
}
children = [
self.resource_setup,
self.setup_message,
]
display(*children)
else:
self._setup_new_code_output.layout = {
"width": self._output_width,
"border": "none",
}
class SshConnectionState(enum.Enum):
waiting_for_input = -1
enter_password = 0
success = 1
keys_already_present = 2
do_you_want_to_continue = 3
no_keys = 4
unknown_hostname = 5
connection_refused = 6
end_of_file = 7
class SshComputerSetup(ipw.VBox):
"""Setup a passwordless access to a computer."""
ssh_config = tl.Dict()
ssh_connection_state = tl.UseEnum(
SshConnectionState, allow_none=True, default_value=None
)
SSH_POSSIBLE_RESPONSES = [
# order matters! the index will return by pexpect and compare
# with SshConnectionState
"[Pp]assword:", # 0
"Now try logging into", # 1
"All keys were skipped because they already exist on the remote system", # 2
"Are you sure you want to continue connecting (yes/no)?", # 3
"ERROR: No identities found", # 4
"Could not resolve hostname", # 5
"Connection refused", # 6
pexpect.EOF, # 7
]
message = tl.Unicode()
password_message = tl.Unicode("The passwordless enabling log.")
def __init__(self, ssh_folder: Path | None = None, **kwargs):
"""Setup a passwordless access to a computer."""
# ssh folder init
if ssh_folder is None:
ssh_folder = Path.home() / ".ssh"
if not ssh_folder.exists():
ssh_folder.mkdir()
ssh_folder.chmod(0o700)
self._ssh_folder = ssh_folder
self._ssh_connection_message = None
self._password_message = ipw.HTML()
tl.dlink(
(self, "password_message"),
(self._password_message, "value"),
transform=lambda x: f"<b>SSH log: {x}</b>",
)
self._ssh_password = ipw.Password(
description="password:",
disabled=False,
layout=LAYOUT,
style=STYLE,
)
# Don't show the continue button until it ask for password the
# second time, which happened when the proxy jump is set. The
# first time it ask for password is for the jump host.
self._continue_with_password_button = ipw.Button(
description="Continue",
layout={"width": "100px", "display": "none"},
)
self._continue_with_password_button.on_click(self._send_password)
self.password_box = ipw.VBox(
[
ipw.HBox([self._ssh_password, self._continue_with_password_button]),
self._password_message,
]
)
# Username.
self.username = ipw.Text(description="Username:", layout=LAYOUT, style=STYLE)
# Port.
self.port = ipw.IntText(
description="Port:",
value=22,
layout=LAYOUT,
style=STYLE,
)
# Hostname.
self.hostname = ipw.Text(
description="Computer hostname:",
layout=LAYOUT,
style=STYLE,
)
# ProxyJump.
self.proxy_jump = ipw.Text(
description="ProxyJump:",
layout=LAYOUT,
style=STYLE,
)
# ProxyJump.
self.proxy_command = ipw.Text(
description="ProxyCommand:",
layout=LAYOUT,
style=STYLE,
)
self._inp_private_key = ipw.FileUpload(
accept="",
layout=LAYOUT,
description="Private key",
multiple=False,
)
self._verification_mode = ipw.Dropdown(
options=[
("Password", "password"),
("Use custom private key", "private_key"),
("Download public key", "public_key"),
("Multiple factor authentication", "mfa"),
],
layout=LAYOUT,
style=STYLE,
value="password",
description="Verification mode:",
disabled=False,
)
self._verification_mode.observe(
self._on_verification_mode_change, names="value"
)
self._verification_mode_output = ipw.Output()
self._continue_button = ipw.ToggleButton(
description="Continue", layout={"width": "100px"}, value=False
)
# Setup ssh button and output.
btn_setup_ssh = ipw.Button(description="Setup ssh")
btn_setup_ssh.on_click(self._on_setup_ssh_button_pressed)
children = [
self.hostname,
self.port,
self.username,
self.proxy_jump,
self.proxy_command,
self._verification_mode,
self._verification_mode_output,
btn_setup_ssh,
]
super().__init__(children, **kwargs)
def _ssh_keygen(self):
"""Generate ssh key pair."""
self.message = wrap_message(
"Generating SSH key pair.",
MessageLevel.SUCCESS,
)
fpath = self._ssh_folder / "id_rsa"
keygen_cmd = [
"ssh-keygen",
"-f",
fpath,
"-t",
"rsa",
"-b",
"4096",
"-m",
"PEM",
"-N",
"",
]
if not fpath.exists():
subprocess.run(keygen_cmd, capture_output=True)
def _can_login(self):
"""Check if it is possible to login into the remote host."""
# With BatchMode on, no password prompt or other interaction is attempted,
# so a connect that requires a password will fail.
ret = subprocess.call(
[
"ssh",
self.hostname.value,
"-o",
"BatchMode=yes",
"-o",
"ConnectTimeout=5",
"true",
]
)
return ret == 0
def _is_in_config(self):
"""Check if the SSH config file contains host information."""
config_path = self._ssh_folder / "config"
if not config_path.exists():
return False
sshcfg = aiida_ssh_plugin.parse_sshconfig(self.hostname.value)
# NOTE: parse_sshconfig returns a dict with a hostname
# even if it is not in the config file.
# We require at least the user to be specified.
if "user" not in sshcfg:
return False
return True
def _write_ssh_config(self, private_key_abs_fname=None):
"""Put host information into the config file."""
config_path = self._ssh_folder / "config"
self.message = wrap_message(
f"Adding {self.hostname.value} section to {config_path}",
MessageLevel.SUCCESS,
)
with open(config_path, "a") as file:
file.write(f"Host {self.hostname.value}\n")
file.write(f" User {self.username.value}\n")
file.write(f" Port {self.port.value}\n")
if self.proxy_jump.value != "":
file.write(
f" ProxyJump {self.proxy_jump.value.format(username=self.username.value)}\n"
)
if self.proxy_command.value != "":
file.write(
f" ProxyCommand {self.proxy_command.value.format(username=self.username.value)}\n"
)
if private_key_abs_fname:
file.write(f" IdentityFile {private_key_abs_fname}\n")
file.write(" ServerAliveInterval 5\n")
def key_pair_prepare(self):
"""Prepare key pair for the ssh connection."""
# Always start by generating a key pair if they are not present.
self._ssh_keygen()
# If hostname & username are not provided - do not do anything.
if self.hostname.value == "": # check hostname
message = "Please specify the computer name (for SSH)"
raise ValueError(message)
if self.username.value == "": # check username
message = "Please specify your SSH username."
raise ValueError(message)
def thread_ssh_copy_id(self):
"""Copy public key on the remote computer, on a separate thread."""
ssh_connection_thread = threading.Thread(target=self._ssh_copy_id)
ssh_connection_thread.start()
def _on_setup_ssh_button_pressed(self, _=None):
"""Setup ssh connection."""
if self._verification_mode.value == "password":
try:
self.key_pair_prepare()
except ValueError as exc:
self.message = wrap_message(str(exc), MessageLevel.ERROR)
return
self.thread_ssh_copy_id()
# For not password ssh auth (such as using private_key or 2FA), key pair is not needed (2FA)
# or the key pair is ready.
# There are other mechanism to set up the ssh connection.
# But we still need to write the ssh config to the ssh config file for such as
# proxy jump.
private_key_fname = None
if self._verification_mode.value == "private_key":
# Write private key in ~/.ssh/ and use the name of upload file,
# if exist, generate random string and append to filename then override current name.
# unwrap private key file and setting temporary private_key content
private_key_fname, private_key_content = self._private_key
if private_key_fname is None: # check private key file
message = "Please upload your private key file."
self.message = wrap_message(message, MessageLevel.ERROR)
return
filename = Path(private_key_fname).name
# if the private key filename is exist, generate random string and append to filename subfix
# then override current name.
if filename in [str(p.name) for p in Path(self._ssh_folder).iterdir()]:
private_key_fpath = self._ssh_folder / f"{filename}-{shortuuid.uuid()}"
self._add_private_key(private_key_fpath, private_key_content)
# TODO(danielhollas): I am not sure this is correct. What if the user wants
# to overwrite the private key? Or any other config? The configuration would never be written.
# And the user is not notified that we did not write anything.
# https://github.com/aiidalab/aiidalab-widgets-base/issues/516
if not self._is_in_config():
self._write_ssh_config(private_key_abs_fname=private_key_fname)
def _ssh_copy_id(self):
"""Run the ssh-copy-id command and follow it until it is completed."""
timeout = 10
self.password_message = f"Sending public key to {self.hostname.value}... "
self._ssh_connection_process = pexpect.spawn(
f"ssh-copy-id {self.hostname.value}"
)
while True:
try:
idx = self._ssh_connection_process.expect(
self.SSH_POSSIBLE_RESPONSES,
timeout=timeout,
)
self.ssh_connection_state = SshConnectionState(idx)
except pexpect.TIMEOUT:
self.password_message = f"Exceeded {timeout} s timeout. Please check you username and password and try again."
break
# Terminating the process when nothing else can be done.
if self.ssh_connection_state in (
SshConnectionState.success,
SshConnectionState.keys_already_present,
SshConnectionState.no_keys,
SshConnectionState.unknown_hostname,
SshConnectionState.connection_refused,
SshConnectionState.end_of_file,
):
break
self._ssh_connection_message = None
self._ssh_connection_process = None
def _send_password(self, _=None):
self._continue_with_password_button.disabled = True
self._ssh_connection_process.sendline(self._ssh_password.value)
@tl.observe("ssh_connection_state")
def _observe_ssh_connnection_state(self, _=None):
"""Observe the ssh connection state and act according to the changes."""
if self.ssh_connection_state is SshConnectionState.waiting_for_input:
return
if self.ssh_connection_state is SshConnectionState.success:
self.password_message = (
"The passwordless connection has been set up successfully."
)
return
if self.ssh_connection_state is SshConnectionState.keys_already_present:
self.password_message = "The passwordless connection has already been setup. Nothing to be done."
return
if self.ssh_connection_state is SshConnectionState.no_keys:
self.password_message = (
" Failed\nLooks like the key pair is not present in ~/.ssh folder."
)
return
if self.ssh_connection_state is SshConnectionState.unknown_hostname:
self.password_message = "Failed\nUnknown hostname."
return
if self.ssh_connection_state is SshConnectionState.connection_refused:
self.password_message = "Failed\nConnection refused."
return
if self.ssh_connection_state is SshConnectionState.end_of_file:
self.password_message = (
"Didn't manage to connect. Please check your username/password."
)
return
if self.ssh_connection_state is SshConnectionState.enter_password:
self._handle_ssh_password()
elif self.ssh_connection_state is SshConnectionState.do_you_want_to_continue:
self._ssh_connection_process.sendline("yes")
def _handle_ssh_password(self):
"""Send a password to a remote computer."""
message = (
self._ssh_connection_process.before.splitlines()[-1]
+ self._ssh_connection_process.after
)
if self._ssh_connection_message == message:
self._ssh_connection_process.sendline(self._ssh_password.value)
else:
self.password_message = (
f"Please enter {self.username.value}@{self.hostname.value}'s password:"
if message == b"Password:"
else f"Please enter {message.decode('utf-8')}"
)
self._ssh_password.disabled = False
self._continue_with_password_button.disabled = False
self._ssh_connection_message = message
# If user did not provide a password, we wait for the input.
# Otherwise, we send the password.
if self._ssh_password.value == "":
self.ssh_connection_state = SshConnectionState.waiting_for_input
else:
self.password_message = 'Sending password <i class="fa fa-spinner" aria-hidden="true"></i> (timeout 10s)'
self._send_password()
def _on_verification_mode_change(self, change):
"""which verification mode is chosen."""
with self._verification_mode_output:
clear_output()
if self._verification_mode.value == "private_key":
display(self._inp_private_key)
elif self._verification_mode.value == "public_key":
public_key = self._ssh_folder / "id_rsa.pub"
if public_key.exists():
display(
ipw.HTML(
f"""<pre style="background-color: #253239; color: #cdd3df; line-height: normal; custom=test">{public_key.read_text()}</pre>""",
layout={"width": "100%"},
)
)
@property
def _private_key(self) -> tuple[str | None, bytes | None]:
"""Unwrap private key file and setting filename and file content."""
if self._inp_private_key.value:
(fname, _value), *_ = self._inp_private_key.value.items()
content = copy.copy(_value["content"])
self._inp_private_key.value.clear()
self._inp_private_key._counter = 0 # pylint: disable=protected-access
return fname, content
return None, None
@staticmethod
def _add_private_key(private_key_fpath: Path, private_key_content: bytes):
"""Write private key to the private key file in the ssh folder."""
private_key_fpath.write_bytes(private_key_content)
private_key_fpath.chmod(0o600)
def _reset(self):
self.hostname.value = ""
self.port.value = 22
self.username.value = ""
self.proxy_jump.value = ""
self.proxy_command.value = ""
@tl.observe("ssh_config")
def _observe_ssh_config(self, change):
"""Pre-filling the input fields."""
self._reset()
new_ssh_config = change["new"]
if "hostname" in new_ssh_config:
self.hostname.value = new_ssh_config["hostname"]
if "username" in new_ssh_config:
self.username.value = new_ssh_config["username"]
if "port" in new_ssh_config:
self.port.value = int(new_ssh_config["port"])
if "proxy_jump" in new_ssh_config:
self.proxy_jump.value = new_ssh_config["proxy_jump"]
if "proxy_command" in new_ssh_config:
self.proxy_command.value = new_ssh_config["proxy_command"]
class AiidaComputerSetup(ipw.VBox):
"""Inform AiiDA about a computer."""
computer_setup = tl.Dict(allow_none=True)
computer_configure = tl.Dict(allow_none=True)
message = tl.Unicode()
def __init__(self, **kwargs):
self._on_setup_computer_success = []
# List of widgets to be displayed.
self.label = ipw.Text(
value="",
placeholder="Will only be used within AiiDA",
description="Computer name:",
layout=LAYOUT,
style=STYLE,
)
# Hostname.
self.hostname = ipw.Text(description="Hostname:", layout=LAYOUT, style=STYLE)
# Computer description.
self.description = ipw.Text(
value="",
placeholder="No description (yet)",
description="Computer description:",
layout=LAYOUT,
style=STYLE,
)
# Directory where to run the simulations.
self.work_dir = ipw.Text(
value="",
placeholder="/home/{username}/aiida_run",
description="AiiDA working directory:",
layout=LAYOUT,
style=STYLE,
)
# Mpirun command.
self.mpirun_command = ipw.Text(
value="mpirun -n {tot_num_mpiprocs}",
description="Mpirun command:",
layout=LAYOUT,
style=STYLE,
)
# Number of CPUs per node.
self.mpiprocs_per_machine = ipw.IntText(
value=1,
step=1,
description="#CPU(s) per node:",
layout=LAYOUT,
style=STYLE,
)
# Memory per node.
self.default_memory_per_machine_widget = ipw.Text(
value="",
placeholder="not specified",
description="Memory per node:",
layout=LAYOUT,
style=STYLE,
)
memory_wrong_syntax = ipw.HTML(
value="""<i class="fa fa-times" style="color:red;font-size:2em;" ></i> wrong syntax""",
)
memory_wrong_syntax.layout.display = "none"
self.default_memory_per_machine = None
def observe_memory_per_machine(change):
"""Check if the string defining memory is valid."""
memory_wrong_syntax.layout.display = "none"
if not self.default_memory_per_machine_widget.value:
self.default_memory_per_machine = None
return
try:
self.default_memory_per_machine = (
int(parse_size(change["new"], binary=True) / 1024) or None
)
memory_wrong_syntax.layout.display = "none"
except InvalidSize:
memory_wrong_syntax.layout.display = "block"
self.default_memory_per_machine = None
self.default_memory_per_machine_widget.observe(
observe_memory_per_machine, names="value"
)
# Transport type.
self.transport = ipw.Dropdown(
value="core.local",
options=plugins.entry_point.get_entry_point_names("aiida.transports"),
description="Transport type:",
style=STYLE,
)
# Safe interval.
self.safe_interval = ipw.FloatText(
value=30.0,
description="Min. connection interval (sec):",
layout=LAYOUT,
style=STYLE,
)
# Scheduler.
self.scheduler = ipw.Dropdown(
value="core.slurm",
options=plugins.entry_point.get_entry_point_names("aiida.schedulers"),
description="Scheduler:",
style=STYLE,
)
self.shebang = ipw.Text(
value="#!/usr/bin/env bash",
description="Shebang:",
layout=LAYOUT,
style=STYLE,
)
# Use double quotes to escape.
self.use_double_quotes = ipw.Checkbox(
value=False,
description="Use double quotes to escape environment variable of job script.",
)
# Use login shell.
self.use_login_shell = ipw.Checkbox(value=True, description="Use login shell")
# Prepend text.
self.prepend_text = ipw.Textarea(
placeholder="Text to prepend to each command execution",
description="Prepend text:",
layout=LAYOUT,
)
# Append text.
self.append_text = ipw.Textarea(
placeholder="Text to append to each command execution",
description="Append text:",
layout=LAYOUT,
)
# Buttons and outputs.
self.setup_button = ipw.Button(description="Setup computer")
self.setup_button.on_click(self.on_setup_computer)
test_button = ipw.Button(description="Test computer")
test_button.on_click(self.test)
self._test_out = ipw.HTML(layout=LAYOUT)
# Organize the widgets
children = [
self.label,
self.hostname,
self.description,
self.work_dir,
self.mpirun_command,
self.mpiprocs_per_machine,
ipw.HBox([self.default_memory_per_machine_widget, memory_wrong_syntax]),
self.transport,
self.safe_interval,
self.scheduler,
self.shebang,
self.use_login_shell,
self.use_double_quotes,
self.prepend_text,
self.append_text,
self.setup_button,
test_button,
self._test_out,
]
super().__init__(children, **kwargs)
def _configure_computer(self, computer: orm.Computer, transport: str):
# Use default AiiDA user
user = orm.User.collection.get_default()
if transport == "core.ssh":
self._configure_computer_ssh(computer, user)
elif transport == "core.local":
self._configure_computer_local(computer, user)
else:
msg = f"invalid transport type '{transport}'"
raise common.ValidationError(msg)
def _configure_computer_ssh(self, computer: orm.Computer, user: orm.User):
"""Configure the computer with SSH transport
There are three sources of authparams information ordered by priority increase:
- the default values
- the SSH config file
- the computer_configure dictionary
At the moment, there is no overlap between the SSH config file and the computer_configure dictionary.
The proxyjump and proxycommend can be read from both the SSH config file and the computer_configure dictionary,
since the SSH config file is generated from the computer_configure dictionary in `SshComputerSetup._write_ssh_config`.
"""
sshcfg = aiida_ssh_plugin.parse_sshconfig(self.hostname.value)
authparams = {
"port": int(sshcfg.get("port", 22)),
"look_for_keys": True,
"key_filename": str(
Path(sshcfg.get("identityfile", ["~/.ssh/id_rsa"])[0]).expanduser()
),
"timeout": 60,
"allow_agent": True,
"proxy_jump": "",
"proxy_command": "",
"compress": True,
"gss_auth": False,
"gss_kex": False,
"gss_deleg_creds": False,
"gss_host": self.hostname.value,
"load_system_host_keys": True,
"key_policy": "WarningPolicy",
"use_login_shell": self.use_login_shell.value,
"safe_interval": self.safe_interval.value,
}
if "username" in self.computer_configure:
authparams["username"] = self.computer_configure["username"]
else:
try:
# This require the Ssh connection setup is done before the computer setup
authparams["username"] = sshcfg["user"]
except KeyError as exc:
message = "SSH username is not provided"
raise RuntimeError(message) from exc
if "proxy_jump" in self.computer_configure:
authparams["proxy_jump"] = self.computer_configure["proxy_jump"]
if "proxy_command" in self.computer_configure:
authparams["proxy_command"] = self.computer_configure["proxy_command"]
if "key_filename" in self.computer_configure:
authparams["key_filename"] = str(
Path(self.computer_configure["key_filename"]).expanduser()
)
if "key_policy" in self.computer_configure:
authparams["key_policy"] = self.computer_configure["key_policy"]
computer.configure(user=user, **authparams)
return True
def _configure_computer_local(self, computer: orm.Computer, user: orm.User):
"""Configure the computer with local transport"""
authparams = {
"use_login_shell": self.use_login_shell.value,
"safe_interval": self.safe_interval.value,
}
computer.configure(user=user, **authparams)
return True
def _run_callbacks_if_computer_exists(self, label):
"""Run things on an existing computer"""
if self._computer_exists(label):
for function in self._on_setup_computer_success:
function()
return True
return False
def _computer_exists(self, label):
try:
orm.load_computer(label=label)
except common.NotExistent:
return False
return True
def _validate_computer_settings(self):
if self.label.value == "": # check computer label
self.message = wrap_message(
"Please specify the computer name (for AiiDA)",
MessageLevel.WARNING,
)
return False
if self.work_dir.value == "":
self.message = wrap_message(
"Please specify working directory",
MessageLevel.WARNING,
)
return False
if self.hostname.value == "":
self.message = wrap_message(
"Please specify hostname",
MessageLevel.WARNING,
)
return False
return True
def on_setup_computer(self, _=None):
"""Create a new computer."""
if not self._validate_computer_settings():
return False
# If the computer already exists, we just run the registered functions and return
if self._run_callbacks_if_computer_exists(self.label.value):
self.message = wrap_message(
f"A computer {self.label.value} already exists. Skipping creation.",
MessageLevel.INFO,
)
return True
items_to_configure = [
"label",
"hostname",
"description",
"work_dir",
"mpirun_command",
"mpiprocs_per_machine",
"transport",
"use_double_quotes",
"scheduler",
"prepend_text",
"append_text",
"shebang",
]
kwargs = {key: getattr(self, key).value for key in items_to_configure}
computer_builder = ComputerBuilder(
default_memory_per_machine=self.default_memory_per_machine, **kwargs
)
try:
computer = computer_builder.new()
self._configure_computer(computer, self.transport.value)
computer.store()
except (
ComputerBuilder.ComputerValidationError,
common.exceptions.ValidationError,
RuntimeError,
) as err:
self.message = wrap_message(
f"Computer setup failed! {type(err).__name__}: {err}",
MessageLevel.ERROR,
)
return False
# Callbacks will not run if the computer is not stored
if self._run_callbacks_if_computer_exists(self.label.value):
self.message = wrap_message(
f"Computer<{computer.pk}> {computer.label} created",