-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathkeck_vnc_launcher.py
More file actions
2054 lines (1747 loc) · 82.1 KB
/
keck_vnc_launcher.py
File metadata and controls
2054 lines (1747 loc) · 82.1 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
#! /usr/bin/env python3
## Import standard modules
import os
import argparse
import atexit
import datetime
import json
import logging
import os
from pathlib import Path
import platform
import re
import socket
import subprocess
import sys
from threading import Thread
import time
import traceback
import requests
import yaml
## Import local modules
import soundplay
## Module vars
__version__ = '3.0.5'
supportEmail = 'remote-observing@keck.hawaii.edu'
KRO_API = 'https://www3.keck.hawaii.edu/api/kroApi/'
SESSION_NAMES = ('control0', 'control1', 'control2',
'analysis0', 'analysis1', 'analysis2',
'telanalys', 'telstatus')
KROException = Exception
##-------------------------------------------------------------------------
## Main
##-------------------------------------------------------------------------
def main():
args = create_parser()
create_logger(args)
kvl = KeckVncLauncher(args)
#catch all exceptions so we can exit gracefully
try:
kvl.start()
except Exception as error:
kvl.handle_fatal_error(error)
##-------------------------------------------------------------------------
## Create argument parser
##-------------------------------------------------------------------------
def create_parser():
## create a parser object for understanding command-line arguments
description = (f"Keck VNC Launcher (v{__version__}). This program is used "
f"by approved Keck Remote Observing sites to launch VNC "
f"sessions for the specified instrument account. For "
f"help or information on how to configure the code, please "
f"see the included README.md file or email "
f"{supportEmail}")
parser = argparse.ArgumentParser(description=description)
## add flags
parser.add_argument("--test", dest="test",
default=False, action="store_true",
help="Test system rather than connect to VNC sessions.")
parser.add_argument("--authonly", dest="authonly",
default=False, action="store_true",
help="Authenticate through firewall, but do not start VNC sessions.")
parser.add_argument("--nosound", dest="nosound",
default=False, action="store_true",
help="Skip start of soundplay application.")
parser.add_argument("--viewonly", dest="viewonly",
default=False, action="store_true",
help="Open VNC sessions in View Only mode (only for TigerVnC viewer)")
parser.add_argument("-v", "--verbose", dest="verbose",
default=False, action="store_true",
help="Be verbose.")
for name in SESSION_NAMES:
parser.add_argument(f"--{name}",
dest=name,
default=False,
action="store_true",
help=f"Open {name} VNC session")
## add arguments
parser.add_argument("account", type=str.lower, nargs='?', default='',
help="The user account.")
## add options
parser.add_argument("-c", "--config", dest="config", type=str,
help="Path to local configuration file.")
parser.add_argument("--vncserver", type=str,
help="Name of VNC server to connect to. Takes precedence over all.")
parser.add_argument( '--vncports', nargs='+', type=str,
help="Numerical list of VNC ports to connect to. Takes precedence over all.")
#parse
args = parser.parse_args()
## If authonly is set, also set nosound because if the user doesn't want
## VNCs, they likely don't want sound as well.
if args.authonly is True:
args.nosound = True
## Change default behavior if no account is given.
if args.account == '':
## Message user to specify an instrument account
print()
print(" ----------------------------------------------------------------")
print(" Due to updates to Keck's internal security systems, we no longer")
print(" support running start_keck_viewers without an instrument account")
print(" argument.")
print()
print(" If you wish to authenticate through the firewall without opening")
print(" VNC sessions, run start_keck_viewers with an instrument account")
print(" and the --authonly flag.")
print(" ----------------------------------------------------------------")
print()
sys.exit(0)
return args
##-------------------------------------------------------------------------
## Create logger
##-------------------------------------------------------------------------
def create_logger(args):
## Create logger object
log = logging.getLogger('KRO')
## Only add handlers if none already exist (eliminates duplicate lines)
if len(log.handlers) > 0:
return
#create log file and log dir if not exist
log_path = Path(__file__).parent / 'logs'
try:
log_path.mkdir(parents=True, exist_ok=True)
except PermissionError as error:
print(str(error))
print(f"ERROR: Unable to create logger at {log_path}")
print("Make sure you have write access to this directory.\n")
log.info("EXITING APP\n")
sys.exit(1)
# Set up formats
logFormat_no_time = logging.Formatter(' %(levelname)8s: %(message)s')
logFormat_no_time.converter = time.gmtime
logFormat_with_time = logging.Formatter('%(asctime)s UT - %(levelname)s: %(message)s')
logFormat_with_time.converter = time.gmtime
#stream/console handler
logConsoleHandler = logging.StreamHandler()
if args.verbose is True:
logConsoleHandler.setLevel(logging.DEBUG)
logConsoleHandler.setFormatter(logFormat_with_time)
else:
logConsoleHandler.setLevel(logging.INFO)
logConsoleHandler.setFormatter(logFormat_no_time)
log.addHandler(logConsoleHandler)
#file handler (full debug logging)
try:
# Works with latest python versions (>=3.12)
ymd = datetime.datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')
except:
# Works with older pyhon versions (>=3.9)
ymd = datetime.datetime.utcnow().strftime('%Y%m%d_%H%M%S')
logFile = log_path / f'keck-remote-log-utc-{ymd}.txt'
logFileHandler = logging.FileHandler(logFile)
logFileHandler.setLevel(logging.DEBUG)
logFileHandler.setFormatter(logFormat_with_time)
log.addHandler(logFileHandler)
##-------------------------------------------------------------------------
## Is the local port in use?
##-------------------------------------------------------------------------
def is_local_port_in_use_lsof(port):
'''Determine if the specified local port is in use using the lsof
command line tool.
'''
cmd = f'lsof -i -P -n | grep LISTEN | grep ":{port} (LISTEN)" | grep -v grep'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
data = proc.communicate()[0]
data = data.decode("utf-8").strip()
return (len(data) != 0)
def is_local_port_in_use_socket(port):
'''Determine if the specified local port is in use using the python
socket package.
'''
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('localhost', port)) == 0
is_local_port_in_use = is_local_port_in_use_socket
##-------------------------------------------------------------------------
## Define VNC Session Object
##-------------------------------------------------------------------------
class VNCSession(object):
'''An object to contain information about a VNC session.
'''
def __init__(self, name=None, display=None, desktop=None, user=None, pid=None):
if name is None and display is not None:
try:
name = desktop.split('-')[2]
except IndexError:
name = desktop
self.name = name
self.display = display
self.desktop = desktop
self.user = user
self.pid = pid
def __str__(self):
return f" {self.name:12s} {self.display:5s}"
##-------------------------------------------------------------------------
## Define SSH Tunnel Object
##-------------------------------------------------------------------------
class SSHTunnel(object):
'''An object to contain information about an SSH tunnel.
'''
def __init__(self, server, username, ssh_pkey, remote_port, local_port,
session_name='unknown', timeout=10,
ssh_additional_kex=None,
ssh_additional_hostkeyalgo=None,
ssh_additional_keytypes=None,
ssh_command='ssh',
proxy_jump=None):
self.log = logging.getLogger('KRO')
self.server = server
self.username = username
self.ssh_pkey = ssh_pkey
self.remote_port = remote_port
self.local_port = local_port
self.session_name = session_name
self.remote_connection = f'{username}@{server}:{remote_port}'
self.ssh_additional_kex = ssh_additional_kex
self.ssh_additional_hostkeyalgo = ssh_additional_hostkeyalgo
self.ssh_additional_keytypes = ssh_additional_keytypes
address_and_port = f"{username}@{server}:{remote_port}"
self.log.info(f"Opening SSH tunnel for {address_and_port} "
f"on local port {local_port}.")
# We now know everything we need to know in order to establish the
# tunnel. Build the command line options and start the child process.
# The -N and -T options below are somewhat exotic: they request that
# the login process not execute any commands and that the server does
# not allocate a pseudo-terminal for the established connection.
forwarding = f"{local_port}:localhost:{remote_port}"
if proxy_jump is None:
cmd = [ssh_command, server, '-l', username, '-L', forwarding, '-N', '-T', '-x']
else:
cmd = [ssh_command, '-J', f"{username}@{proxy_jump}", f"{username}@{server}", '-L', forwarding, '-N', '-T', '-x']
cmd.append('-oStrictHostKeyChecking=no')
cmd.append('-oCompression=yes')
if self.ssh_additional_kex is not None:
cmd.append('-oKexAlgorithms=' + self.ssh_additional_kex)
if self.ssh_additional_hostkeyalgo is not None:
cmd.append('-oHostKeyAlgorithms=' + self.ssh_additional_hostkeyalgo)
if self.ssh_additional_keytypes is not None:
cmd.append('-oPubkeyAcceptedKeyTypes=' + self.ssh_additional_keytypes)
if ssh_pkey is not None:
cmd.append('-i')
cmd.append(ssh_pkey)
self.command = ' '.join(cmd)
self.log.debug(f'ssh command: {self.command}')
self.proc = subprocess.Popen(cmd, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
# Having started the process let's make sure it's actually running.
# First try polling, then confirm the requested local port is in use.
# It's a fatal error if either check fails.
if self.proc.poll() is not None:
raise RuntimeError('subprocess failed to execute ssh')
# A delay is built-in here as it takes some finite amount of time for
# ssh to establish the tunnel.
waittime = 0.1
checks = int(timeout/waittime)
while checks > 0:
result = is_local_port_in_use(local_port)
if result == True:
break
elif self.proc.poll() is not None:
raise RuntimeError('ssh command exited unexpectedly')
checks -= 1
time.sleep(waittime)
if checks == 0:
raise RuntimeError(f'ssh tunnel failed to open after {timeout:.0f} seconds')
def close(self):
'''Close this SSH tunnel
'''
self.log.info(f" Closing SSH tunnel for local port {self.local_port}: {self.session_name}")
self.proc.kill()
def __str__(self):
address_and_port = f"{self.username}@{self.server}:{self.remote_port}"
return f"SSH tunnel for {address_and_port} on local port {self.local_port}."
##-------------------------------------------------------------------------
## Define SSH Proxy Object
##-------------------------------------------------------------------------
class SSHProxy(object):
'''An object to contain information about an SSH proxy.
'''
def __init__(self, server, username, ssh_pkey, local_port,
session_name='unknown', timeout=10,
ssh_additional_kex=None,
ssh_additional_hostkeyalgo=None,
ssh_additional_keytypes=None,
ssh_command='ssh',
):
self.log = logging.getLogger('KRO')
self.server = server
self.username = username
self.ssh_pkey = ssh_pkey
self.local_port = local_port
self.session_name = session_name
self.remote_connection = f'{username}@{server}'
self.ssh_additional_kex = ssh_additional_kex
self.ssh_additional_hostkeyalgo = ssh_additional_hostkeyalgo
self.ssh_additional_keytypes = ssh_additional_keytypes
# We now know everything we need to know in order to establish the
# tunnel. Build the command line options and start the child process.
# The -N and -T options below are somewhat exotic: they request that
# the login process not execute any commands and that the server does
# not allocate a pseudo-terminal for the established connection.
cmd = [ssh_command, server, '-l', username, '-N', '-T', '-x', '-D', f"{local_port}"]
cmd.append('-oStrictHostKeyChecking=no')
cmd.append('-oCompression=yes')
if self.ssh_additional_kex is not None:
cmd.append('-oKexAlgorithms=' + self.ssh_additional_kex)
if self.ssh_additional_hostkeyalgo is not None:
cmd.append('-oHostKeyAlgorithms=' + self.ssh_additional_hostkeyalgo)
if self.ssh_additional_keytypes is not None:
cmd.append('-oPubkeyAcceptedKeyTypes=' + self.ssh_additional_keytypes)
if ssh_pkey is not None:
cmd.append('-i')
cmd.append(ssh_pkey)
self.command = ' '.join(cmd)
self.log.debug(f'ssh command: {self.command}')
self.proc = subprocess.Popen(cmd, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
# Having started the process let's make sure it's actually running.
# First try polling, then confirm the requested local port is in use.
# It's a fatal error if either check fails.
if self.proc.poll() is not None:
raise RuntimeError('subprocess failed to execute ssh')
# A delay is built-in here as it takes some finite amount of time for
# ssh to establish the tunnel.
waittime = 0.1
checks = int(timeout/waittime)
while checks > 0:
result = is_local_port_in_use(local_port)
if result == True:
break
elif self.proc.poll() is not None:
raise RuntimeError('ssh command exited unexpectedly')
checks -= 1
time.sleep(waittime)
if checks == 0:
raise RuntimeError(f'ssh tunnel failed to open after {timeout:.0f} seconds')
def close(self):
'''Close this SSH tunnel
'''
self.log.info(f" Closing SSH tunnel for local port {self.local_port}: {self.session_name}")
self.proc.kill()
def __str__(self):
address_and_port = f"{self.username}@{self.server}:{self.remote_port}"
return f"SSH tunnel for {address_and_port} on local port {self.local_port}."
##-------------------------------------------------------------------------
## Define Keck VNC Launcher
##-------------------------------------------------------------------------
class KeckVncLauncher(object):
def __init__(self, args):
#init vars we need to shutdown app properly
self.config = None
self.log = None
self.ssh_command = 'ssh'
self.sound = None
self.ssh_tunnels = dict()
self.vnc_threads = list()
self.vnc_processes = list()
self.firewall_requested = False
self.instrument = None
self.vncserver = None
self.ssh_key_valid = False
self.ssh_additional_kex = None
self.ssh_additional_hostkeyalgo = None
self.ssh_additional_keytypes = None
self.exit = False
self.geometry = list()
self.tigervnc = None
self.vncviewer_has_geometry = None
self.api_data = None
self.args = args
self.log = logging.getLogger('KRO')
#default start sessions
self.default_sessions = []
self.sessions_found = []
#local port start (can be overridden by config file)
self.LOCAL_PORT_START = 5901
#ssh key constants
self.kvnc_account = 'kvnc'
##-------------------------------------------------------------------------
## Start point (main)
##-------------------------------------------------------------------------
def start(self):
'''Start the main program control loop.
This contains the basic sequence of events for running the program.
'''
##---------------------------------------------------------------------
## Parse command line args
self.log.debug("\n***** PROGRAM STARTED *****")
self.log.debug(f"Command: {' '.join(sys.argv)}")
##---------------------------------------------------------------------
## Read configuration
self.get_config()
self.check_config()
if self.args.authonly is False:
self.get_vncviewer_properties()
##---------------------------------------------------------------------
## Log basic system info
self.log_system_info()
self.test_yaml_version()
self.check_version()
if self.args.authonly is False:
self.get_display_info()
##---------------------------------------------------------------------
# Verify Tiger VNC Config
if self.args.authonly is False:
if self.test_tigervnc() > 0:
self.log.error('TigerVNC is not configured properly. See instructions.')
self.log.error('This can have negative effects on other users.')
self.log.error('Exiting program.')
self.exit_app()
##---------------------------------------------------------------------
## Get connect info from API
if self.api_key:
self.get_api_data(self.api_key, self.args.account)
if self.api_data is None:
self.exit_app('API query failed.')
##-----------------------------------------------------------------
## Determine instrument
self.instrument, self.tel = self.determine_instrument(self.args.account)
if self.instrument is None:
self.exit_app(f'Invalid instrument account: "{self.args.account}"')
##-----------------------------------------------------------------
## Determine VNC server
self.vncserver = self.get_vnc_server(self.kvnc_account,
self.instrument)
if self.vncserver is None:
self.exit_app("Could not determine VNC server.")
##---------------------------------------------------------------------
## Run tests
if self.args.test is True:
self.test_all()
self.exit_app()
##---------------------------------------------------------------------
## Open web proxy if requested
if self.config.get('proxy_port', None) is not None:
self.open_ssh_for_proxy()
if self.args.authonly is False:
##-----------------------------------------------------------------
## Determine sessions to open
self.sessions_requested = self.get_sessions_requested(self.args)
##-----------------------------------------------------------------
## Determine VNC Sessions
self.sessions_found = self.get_vnc_sessions(self.vncserver,
self.instrument,
self.kvnc_account,
self.args.account)
if (not self.sessions_found or len(self.sessions_found) == 0):
self.exit_app(f"No VNC sessions found for '{self.args.account}'")
##-----------------------------------------------------------------
## Open requested sessions
self.calc_window_geometry()
if self.args.vncports is not None:
for port in self.args.vncports:
self.start_vnc_session(port)
else:
for session_name in self.sessions_requested:
self.start_vnc_session(session_name)
##-----------------------------------------------------------------
## Open Soundplay
sound = None
if self.args.nosound is False and self.config.get('nosound', False) != True:
self.start_soundplay()
##-----------------------------------------------------------------
## Final output should be connection info
if self.api_data is not None:
self.view_connection_info()
if self.args.authonly is False or self.is_proxy_open():
##---------------------------------------------------------------------
## Wait for quit signal, then all done
atexit.register(self.exit_app, msg="App exit")
self.prompt_menu()
self.exit_app()
##-------------------------------------------------------------------------
## Retrieve or log basic system info
##-------------------------------------------------------------------------
def log_system_info(self):
'''Add info about the local system to the log for debugging
'''
try:
uname_result = os.uname()
self.log.debug(f'System Info: {uname_result}')
if re.search('Microsoft', uname_result.release) is not None\
or re.search('Microsoft', uname_result.version) is not None:
self.log.warning("This system appears to be running linux within "
"a Microsoft Windows environment. While this "
"can work, it is not a supported mode of this "
"software. WMKO will be unable to provide "
"support for this mode of operation.")
hostname = socket.gethostname()
self.log.debug(f'System hostname: {hostname}')
python_version_str = sys.version.replace("\n", " ")
self.log.info(f'Python {python_version_str}')
self.log.debug(f'yaml {yaml.__version__}')
self.log.info(f'Remote Observing Software Version = {__version__}')
except:
self.log.error("Unable to log system info.")
trace = traceback.format_exc()
self.log.debug(trace)
try:
whereisssh = subprocess.check_output(['which', self.ssh_command])
self.log.debug(f'SSH command is {whereisssh.decode().strip()}')
sshversion = subprocess.check_output([self.ssh_command, '-V'],
stderr=subprocess.STDOUT)
self.log.debug(f'SSH version is {sshversion.decode().strip()}')
except:
self.log.error("Unable to log SSH info.")
trace = traceback.format_exc()
self.log.debug(trace)
def check_version(self):
'''Compare the version of the local software against releases available
on GitHub.
'''
url = 'https://api.github.com/repos/KeckObservatory/RemoteObserving/releases'
try:
from packaging import version
self.log.debug("Checking for latest version available on GitHub")
r = requests.get(url, timeout=5)
result = r.json()
remote_version = version.parse(result[0]['name'])
self.log.debug(f'Retrieved remote release version: {remote_version}')
local_version = version.parse(__version__)
if remote_version == local_version:
self.log.info(f'Your software is up to date (v{__version__})')
elif remote_version < local_version:
self.log.info(f'Your software (v{__version__}) is ahead of the released version')
else:
self.log.warning(f'Your local software (v{__version__}) is behind '
f'the currently available version '
f'(v{remote_version})')
if remote_version.base_version == local_version.base_version:
self.log.warning('You may update by running "git pull" in '
'the directory where the software is installed')
except ModuleNotFoundError as e:
self.log.warning("Unable to verify remote version")
self.log.debug(e)
except requests.ConnectionError as e:
self.log.warning("Unable to verify remote version")
self.log.debug(e)
except Exception as e:
self.log.warning("Unable to verify remote version")
self.log.debug(e)
def get_display_info(self):
'''Determine the screen number and size
'''
#get screen dimensions
#alternate command: xrandr |grep \* | awk '{print $1}'
self.log.debug('Determining display info')
self.screens = list()
self.geometry = list()
try:
xpdyinfo = subprocess.run('xdpyinfo', stdout=subprocess.PIPE,
stderr=subprocess.PIPE, timeout=5)
except FileNotFoundError as e:
self.log.debug('xpdyinfo not found')
self.log.debug(e)
return
except subprocess.TimeoutExpired as e:
# If xpdyinfo fails just log and keep going
self.log.debug('xpdyinfo failed')
self.log.debug(e)
return
except TimeoutError as e:
# If xpdyinfo fails just log and keep going
self.log.debug('xpdyinfo failed')
self.log.debug(e)
return
stdout = xpdyinfo.stdout.decode()
if xpdyinfo.returncode != 0:
self.log.debug(f'xpdyinfo failed')
for line in stdout.split('\n'):
self.log.debug(f"xdpyinfo: {line}")
stderr = xpdyinfo.stderr.decode()
for line in stderr.split('\n'):
self.log.debug(f"xdpyinfo: {line}")
return None
find_nscreens = re.search(r'number of screens:\s+(\d+)', stdout)
nscreens = int(find_nscreens.group(1)) if find_nscreens is not None else 1
self.log.debug(f'Number of screens = {nscreens}')
find_dimensions = re.findall(r'dimensions:\s+(\d+)x(\d+)', stdout)
if len(find_dimensions) == 0:
self.log.debug(f'Could not find screen dimensions')
return None
# convert values from strings to int
self.screens = [[int(val) for val in line] for line in find_dimensions]
for screen in self.screens:
self.log.debug(f"Screen size: {screen[0]}x{screen[1]}")
##-------------------------------------------------------------------------
## Get & Check Configuration
##-------------------------------------------------------------------------
def get_config(self):
'''Read the configuration file.
'''
#define files to try loading in order of pref
filenames=['local_config.yaml', 'keck_vnc_config.yaml']
#if config file specified, put that at beginning of list
filename = self.args.config
if filename is not None:
if not Path(filename).is_file():
self.log.error(f'Specified config file "{filename}" does not exist.')
self.exit_app()
else:
filenames.insert(0, filename)
#find first file that exists
file = None
for f in filenames:
if Path(f).is_file():
file = f
break
if file is None:
self.log.error(f'No config files found in list: {filenames}')
self.exit_app()
#load config file and make sure it has the info we need
self.log.info(f'Using config file: {file}')
# open file a first time just to log the raw contents
contents = open(file).read()
self.log.debug(f"Contents of config file:\n{contents}")
# Look for syntax error in configuration file
self.log.debug('Checking config format')
configok = True
lines = contents.split('\n')
for line in lines:
if re.match(r'^([\w_]+):[\w\d\'\"]', line):
self.log.error(f'The format of the config is "keyword: value"')
self.log.error(f'A space is missing in line: {line}')
configok = False
if re.match(r'^\s([\w_]+):\s?[\w\d\'\"]', line):
self.log.error(f'The format of the config is "keyword: value"')
self.log.error(f'There is a leading space in line: {line}')
configok = False
if configok is False:
self.log.error('Exiting app')
sys.exit(1)
# open file a second time to properly read config
config = yaml.load(open(file), Loader=yaml.FullLoader)
for key in ['ssh_path', 'ssh_pkey', 'vncviewer', 'soundplayer', 'aplay']:
if key in config.keys():
config[key] = os.path.expanduser(config[key])
config[key] = os.path.expandvars(config[key])
cstr = "Parsed Configuration:\n"
for key, c in config.items():
cstr += f"\t{key} = " + str(c) + "\n"
self.log.debug(cstr)
self.config = config
# Load some values
self.ssh_command = self.config.get('ssh_path', 'ssh')
self.ssh_pkey = self.config.get('ssh_pkey', None)
lps = self.config.get('local_port_start', None)
self.local_port = self.LOCAL_PORT_START if lps is None else lps
def check_config(self):
'''Do some basic checks on the configuration.
'''
#check API key config
self.api_key = self.config.get('api_key', None)
if self.api_key in [None, '']:
self.log.error("API key is not set.")
else:
self.firewall_requested = True
def get_vncviewer_properties(self):
'''Determine whether we are using TigerVNC
'''
vncviewercmd = self.config.get('vncviewer', 'vncviewer')
cmd = [vncviewercmd, '--help']
self.log.debug(f'Checking VNC viewer: {" ".join(cmd)}')
result = subprocess.run(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output = result.stdout.decode() + '\n' + result.stderr.decode()
if re.search(r'TigerVNC', output):
self.log.info(f'We ARE using TigerVNC')
self.tigervnc = True
else:
self.log.debug(f'We ARE NOT using TigerVNC')
self.tigervnc = False
if re.search(r'[Gg]eometry', output):
self.log.info(f'Found geometry argument')
self.vncviewer_has_geometry = True
else:
self.log.debug(f'Could not find geometry argument')
self.vncviewer_has_geometry = False
# TigerVNC Viewer 64-bit v1.10.1
# VNC(R) Viewer 6.17.731 (r29523) x64 (Aug 3 2017 17:19:47)
self.log.debug(f"VNC Viewer Info:")
for line in output.split('\n'):
if line.strip('\n') != '':
self.log.debug(f" {line}")
version_match = re.search(r'(\d+\.\d+\.\d+)', line)
if version_match is not None:
self.log.debug(f'Matched VNC version pattern: {version_match.group(0)}')
break
def get_api_data(self, api_key, account):
'''Get data from API which contains all info needed to connect.'''
self.api_data = None
#form API url and get data
params = {'key': f'{self.api_key}',
'account': f"{account}"}
tick = datetime.datetime.now()
tick_str = tick.strftime("%H:%M:%S")
self.log.info(f'Calling KRO API at {tick_str} to get account info')
self.log.debug(f'Using URL: {KRO_API} with {params}')
print()
print("-------------------------------------------------------------")
print("Please note: the initial connection to the Keck KRO API may")
print("take up to 1 minute to complete.")
print("-------------------------------------------------------------")
print()
data = None
try:
data = requests.post(KRO_API, data=params, timeout=90)
except Exception as e:
self.log.error(f'Could not get data from API.')
self.log.error(str(e))
return
try:
self.log.debug(data.text)
data = json.loads(data.text)
for key in data.keys():
self.log.debug(f" Got data for {key}: {data[key]}")
tock = datetime.datetime.now()
duration = (tock-tick).total_seconds()
self.log.debug(f'API call took {duration:.1f} s')
except Exception as e:
self.log.error(f'Could not parse data from API.')
self.log.error(str(e))
return
if data is None:
self.log.error('No response from API.')
return
#Look for any errors
stdmsg = ('API failed to retrieve connection info. Please try again. '
f'If this reoccurs, email us at {supportEmail} or create a support ticket at: '
'https://keckobservatory.atlassian.net/servicedesk/customer/portals '
'and be sure to attach the log file.')
stdmsg2 = ('Please check your Keck Observer Homepage for information '
'regarding when your key is approved and deployed according '
'to the observing schedule.')
api_err_map = {
'DATABASE_ERROR': stdmsg,
'FIREWALL_INFO_ERROR': stdmsg,
'INSTRUMENT_ACCOUNT_ERROR': f'API does not recognize instrument account "{self.args.account}"',
'KVNC_INFO_ERROR': stdmsg,
'KVNC_STATUS_ERROR': stdmsg,
'NO_API_KEY': f'No matching API key found. Please check your "api_key" config value.',
'SSH_KEY_NOT_APPROVED': f'Your SSH key is not yet approved.\n{stdmsg2}',
'SSH_KEY_NOT_DEPLOYED': f'Your SSH key is not deployed.\n{stdmsg2}',
}
code = data.get('apiCode', '').upper()
self.log.debug(f'API response code is: {code}')
if code in api_err_map:
self.log.debug(f'API error code: {code}')
self.log.error(api_err_map[code])
return
if code != 'SUCCESS':
self.log.error(f'Invalid status code returned from API: {code}')
return
#all good
self.api_data = data
self.log.debug('API call was successful')
##-------------------------------------------------------------------------
## Get sessions to open
##-------------------------------------------------------------------------
def get_sessions_requested(self, args):
'''Determine which sessions to open based on command line arguments
'''
sessions = list()
# First check the command line arguments
for session in SESSION_NAMES:
try:
requested = getattr(args, session)
except AttributeError:
continue
if requested == True:
sessions.append(session)
if len(sessions) > 0:
self.log.debug(f'Got {sessions} sessions from command line args')
# Use the configuration file if no command line arguments specified
if len(sessions) == 0:
sessions = self.config.get('default_sessions', [])
self.log.debug(f'Got {sessions} sessions from configuration file')
# Finally use the default sessions list as a last resort
if len(sessions) == 0:
sessions = self.default_sessions
self.log.debug(f'Using default sessions: {sessions}')
self.log.debug(f'Sessions to open: {sessions}')
return sessions
##-------------------------------------------------------------------------
## Determine Instrument
##-------------------------------------------------------------------------
def determine_instrument(self, account):
'''Given an account name, determine the instrument and telescope.
'''
accounts = {'mosfire': [f'mosfire{i}' for i in range(1,10)],
'hires': [f'hires{i}' for i in range(1,10)],
'osiris': [f'osiris{i}' for i in range(1,10)],
'lris': [f'lris{i}' for i in range(1,10)],
'nires': [f'nires{i}' for i in range(1,10)],
'deimos': [f'deimos{i}' for i in range(1,10)],
'esi': [f'esi{i}' for i in range(1,10)],
'nirc2': [f'nirc{i}' for i in range(1,10)],
'nirspec': [f'nspec{i}' for i in range(1,10)],
'kcwi': [f'kcwi{i}' for i in range(1,10)],
'kpf': [f'kpf{i}' for i in range(1,10)],
'k1ao': ['k1obsao'],
'k2ao': ['k2obsao'],
'k1inst': ['k1insttech'],
'k2inst': ['k2insttech'],
'k1pcs': ['k1pcs'],
'k2pcs': ['k2pcs'],
}
accounts['mosfire'].append('moseng')
accounts['hires'].append('hireseng')
accounts['osiris'].append('osrseng')
accounts['lris'].append('lriseng')
accounts['nires'].append('nireseng')
accounts['deimos'].append('dmoseng')
accounts['esi'].append('esieng')
accounts['nirc2'].append('nirc2eng')
accounts['nirspec'].append('nspeceng')
accounts['kcwi'].append('kcwieng')
accounts['kpf'].append('kpfeng')
telescope = {'mosfire': 1,
'hires': 1,
'osiris': 1,
'lris': 1,
'kpf': 1,
'k1ao': 1,
'k1inst': 1,
'k1pcs': 1,
'nires': 2,
'deimos': 2,
'esi': 2,
'nirc2': 2,
'nirspec': 2,
'kcwi': 2,
'k2ao': 2,
'k2inst': 2,
'k2pcs': 2,
}
for instrument in accounts.keys():
if account.lower() in accounts[instrument]:
return instrument, telescope[instrument]
return None, None
##-------------------------------------------------------------------------
## SSH Command
##-------------------------------------------------------------------------
def do_ssh_cmd(self, cmd, server, account):
'''Utility function for opening ssh client, executing command and
closing.
'''
timeout = self.config.get('ssh_timeout', 30)
output = None
self.log.debug(f'Trying SSH connect to {server} as {account}:')
if re.match(r'svncserver\d.keck.hawaii.edu', server) is not None:
self.log.debug('Extending timeout for svncserver connections')
timeout = 60
command = [self.ssh_command, server, '-l', account, '-T', '-x']
if self.args.verbose is True:
command.append('-v')
command.append('-v')