-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpodi_SAMPListener.py
executable file
·1125 lines (869 loc) · 35 KB
/
podi_SAMPListener.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
#!/usr/bin/env python3
"""
This module listens to SAMP message announcing new ODI frames. Each frame is
this automatically quick-reduced, either locally or on a remote-machine via
ssh.
"""
try:
# import sampy
# import xsampy as sampy
import astropy.vo.samp as sampy
except ImportError:
print("For this to work you need the SAMPy package installed")
raise
import os
import sys
import time
import multiprocessing
import datetime
import time
from podi_definitions import *
from podi_commandline import *
import podi_SAMPsetup as setup
if (not setup.use_ssh):
import podi_collectcells
import podi_focus
import podi_logging
import subprocess
import logging
m = multiprocessing.Manager()
process_tracker = m.Queue()
worker_queue = multiprocessing.JoinableQueue()
metadata = {"samp.name":
"QR_listener",
"samp.description.text":
"QuickReduce SAMP Listener",
"samp.icon.url":
"file:///work/podi_devel/test/qr.jpg",
"samp.documentation.url":
"http://members.galev.org/rkotulla/research/podi-pipeline/",
"author.name":
"Ralf Kotulla",
"author.email":
"kotulla@uwm.edu",
"author.affiliation":
"University of Wisconsin - Milwaukee",
"home.page":
"http://members.galev.org/rkotulla/research/podi-pipeline",
"cli1.version":"0.01",
}
character_escape = {
" ": "_",
"\\": "",
"/": "",
"|": "",
"&": "",
";": "",
">": "",
"<": "",
"$": "",
}
def escape_characters(filename):
for bad_character in character_escape:
filename = filename.replace(bad_character, character_escape[bad_character])
return filename
def worker_slave(queue):
"""
This function handles all work, either running collectcells locally or
remotely via ssh. Files to reduce are read from a queue.
"""
logger = logging.getLogger("SAMPWorker")
logger.info("Worker process started, ready for action...")
if (not setup.use_ssh):
# If we reduce frames locally, prepare the QR logging.
options['clobber'] = False
while (True):
try:
# print "\n\nWaiting for stuff to do\n\n"
task = queue.get()
except (KeyboardInterrupt, SystemExit) as e:
# print "worker received termination notice"
# Ignore the shut-down command here, and wait for the official
# shutdown command from main task
continue
if (task is None):
logger.info("Shutting down worker")
queue.task_done()
break
filename, object_name, obsid = task
logger.info("starting work on file %s" % (filename))
ccopts = ""
if (len(sys.argv) > 2):
# There are some parameters to be forwarded to collectcells
ccopts = " ".join(sys.argv[1:])
# print "ccopts=",ccopts
if (cmdline_arg_isset("-dryrun")):
logger.info("DRYRUN: Sending off file %s for reduction" % (filename))
# print "task done!"
queue.task_done()
continue
if (object_name.lower().find("focus") >= 0):
#
# This is most likely a focus exposure
#
n_stars = int(cmdline_arg_set_or_default("-nstars", 7))
logger.info("New focus exposure to analyze (with %d stars)" % (n_stars))
if (setup.use_ssh):
remote_inputfile = setup.translate_filename_local2remote(filename)
kw = {
'user': setup.ssh_user,
'host': setup.ssh_host,
'filename': remote_inputfile,
'podidir': setup.remote_podi_dir,
'outdir': setup.output_dir,
'nstars': n_stars,
}
ssh_command = "ssh %(user)s@%(host)s %(podidir)s/podi_focus.py -nstars=%(nstars)d %(filename)s %(outdir)s" % kw
logger.info("Out-sourcing work to %(user)s@%(host)s via ssh" % kw)
process = subprocess.Popen(ssh_command.split(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
_stdout, _stderr = process.communicate()
process.stdout.close()
process.stderr.close()
try:
process.terminate()
except:
pass
#print "*"*80
if (not _stdout == "" and _stdout is not None):
logger.info("Received STDOUT:\n%s" % (_stdout))
#print "*"*80
if (not _stderr == "" and _stderr is not None):
logger.info("Received STDERR:\n%s" % (_stderr))
#print _stderr
#print "*"*80
else:
# Run locally
logger.info("Analyzing focus sequence (%s) locally" % (filename))
podi_focus.get_focus_measurement(filename, n_stars=n_stars, output_dir=setup.output_dir)
logger.info("Done with analysis")
# Now check if we are supposed to open/display the focus plot
if (setup.focus_display is not None):
remote_filename = "%s/%s_focus.png" % (setup.output_dir, obsid)
local_filename = setup.translate_filename_remote2local(filename, remote_filename)
cmd = "%s %s &" % (setup.focus_display, local_filename)
logger.info("Opening and displaying plot")
os.system(cmd)
else:
#
# This is NOT a focus exposure
#
if (setup.use_ssh):
# This is not a focus exposure, to treat it as a normal science exposure
remote_inputfile = setup.translate_filename_local2remote(filename)
kw = {
'user': setup.ssh_user,
'host': setup.ssh_host,
'collectcells': setup.ssh_executable,
'options': ccopts,
'filename': remote_inputfile,
'outputfile': setup.output_format,
}
ssh_command = "ssh %(user)s@%(host)s %(collectcells)s %(filename)s %(outputfile)s %(options)s -noclobber" % kw
process = subprocess.Popen(ssh_command.split(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
_stdout, _stderr = process.communicate()
process.stdout.close()
process.stderr.close()
try:
process.terminate()
except:
pass
#print "*"*80
if (not _stdout == "" and _stdout is not None):
logger.info("Received STDOUT:\n%s" % (_stdout))
#print "*"*80
if (not _stderr == "" and _stderr is not None):
logger.info("Received STDERR:\n%s" % (_stderr))
#print _stderr
#print "*"*80
else:
logger.info("Running collectcells (%s)" % (filename))
podi_collectcells.collectcells_with_timeout(input=filename,
outputfile=setup.output_format,
options=options,
timeout=300,
process_tracker=process_tracker)
#
# If requested, also send the command to ds9
#
local_filename = setup.translate_filename_remote2local(filename, setup.output_format)
if (cmdline_arg_isset("-forward2ds9")):
forward2ds9_option = cmdline_arg_set_or_default("-forward2ds9", "image")
if (forward2ds9_option == "irafmosaic"):
cmd = "mosaicimage iraf %s" % (local_filename)
else:
cmd = "fits %s" % (local_filename)
logger.info("Forwarding file to ds9")
logger.debug("filename: %s" % (filename))
logger.debug("remote file: %s" % (remote_inputfile))
logger.debug("local file: %s" % (local_filename))
try:
cli1 = sampy.SAMPIntegratedClient(metadata = metadata)
cli1.connect()
cli1.enotify_all(mtype='ds9.set', cmd='frame 2')
cli1.enotify_all(mtype='ds9.set', cmd='scale scope global')
cli1.enotify_all(mtype='ds9.set', cmd=cmd)
cli1.disconnect()
except Exception as err:
logger.error("Problems sending message to ds9: %s" % err)
podi_logging.log_exception()
pass
# By default, also open the psf diagnostic plot, if available
psf_plot_fn = local_filename[:-5]+".psf.png"
if (os.path.isfile(psf_plot_fn)):
cmd = "%s %s &" % (setup.focus_display, psf_plot_fn)
logger.info("Opening and displaying PSF diagnostic plot (%s)" % (psf_plot_fn))
os.system(cmd)
#
# Once the file is reduced, mark the current task as done.
#
logger.info("task done!")
queue.task_done()
print("Terminating worker process...")
return
def get_filename_from_input(input):
"""
Convert the input string, which can be either a FITS filename or a directory,
into a valid FITS filename of one OTA of the exposure.
"""
if (os.path.isfile(input)):
return input
elif (os.path.isdir(input)):
if (input.endswith("/")):
input = input[:-1]
dirname, base = os.path.split(input)
filename = "%s/%s.33.fits" % (input, base)
if (not os.path.isfile(filename)):
filename += ".fz"
if (not os.path.isfile(filename)):
return None
return filename
return filename
return input
def check_obstype(filename):
obstype, object_name, obsid = "", "", ""
with pyfits.open(filename) as hdulist:
obstype = hdulist[0].header['OBSTYPE']
object_name = hdulist[0].header['OBJECT'] \
if 'OBJECT' in hdulist[0].header else ""
obsid = hdulist[0].header['OBSID'] \
if 'OBSID' in hdulist[0].header else ""
return obstype, object_name, obsid
def receive_msg(private_key, sender_id, msg_id, mtype, params, extra):
"""
This function is a callbakc handler that is called everytime a message
is received from the SAMP hub.
"""
logger = logging.getLogger("MsgRevc")
#print "\n"*5,"new file received!\n"
#print private_key, sender_id, msg_id, mtype, params, extra
#cli1.reply(msg_id, {"samp.status": SAMP_STATUS_OK,
# "samp.result": {"result": "ok guys"}})
filename = params['filename']
logger.info("Received command to reduce %s (at %s) ..." % (
filename, datetime.datetime.now().strftime("%H:%M:%S.%f")
))
if (not os.path.isdir(filename)):
logger.error("filename %s is not a valid directory" % (filename))
return
fits_file = get_filename_from_input(filename)
obstype, object_name, obsid = check_obstype(fits_file)
if (obstype == "FOCUS" or
obstype == "OBJECT" or
not cmdline_arg_isset("-onlyscienceframes")):
worker_queue.put( (filename, object_name, obsid) )
else:
logger.info("""
Received input %s
(translated to %s) ...
This is not a OBJECT or FOCUS frame.
I was told to ignore these kind of frames.
\
""" % (filename, fits_file))
return
# worker_queue.put( (filename, object_name, obsid) )
logger.info("Done with this one, hungry for more!")
return
#################################################################################
#
#
# QR swarp-stack functionality
#
# this uses the qr.stack message
#
#
#################################################################################
# define a message queue to handle remote executions
stacking_queue = multiprocessing.JoinableQueue()
def handle_swarp_request(params, logger):
# print "\n================"*3,params,"\n================"*3
str_filelist = params['filelist']
tracking_rate = params['trackrate']
logger.debug("Received 'filelist': %s" % (str_filelist))
logger.debug("Received 'trackrate': %s" % (tracking_rate))
# print "starting work on file",str_filelist
#
# Get rid of all files that do not exist
#
filelist = []
for fitsfile in str_filelist.split(","):
if (os.path.isfile(fitsfile)):
logger.debug("Found valid input file: %s" % (fitsfile))
filelist.append(fitsfile)
elif (os.path.isdir(fitsfile)):
logger.debug("Found directory name")
if (fitsfile[-1] == "/"):
fitsfile = fitsfile[:-1]
basedir, filebase = os.path.split(fitsfile)
fitsfile = "%s/%s.33.fits" % (fitsfile, filebase)
filelist.append(fitsfile)
# print "filelist = ",filelist
# We need at least one file to work on
if (len(filelist) <= 0):
logger.info("No valid files for stacking found!")
return
# queue.task_done()
# continue
# print datetime.datetime.now().strftime("%H:%M:%S.%f")
# print filelist
# print tracking_rate
# print extra
logger.info("Input filelist:\n%s" % ("\n".join([" --> %s" % fn for fn in filelist])))
#("\n".join(filelist)))
#
# Open the first file in the list, get the object name
#
firsthdu = pyfits.open(filelist[0])
object_name = firsthdu[0].header['OBJECT'] \
if 'OBJECT' in firsthdu[0].header else "unknown"
filter_name = firsthdu[0].header['FILTER'] \
if 'FILTER' in firsthdu[0].header else"unknown"
firsthdu.close()
logger.debug("Reference data: object:%s, filter:%s" % (
object_name, filter_name))
# Create a ODI-like timestamp
formatted_timestamp = params['timestamp'].strftime("%Y%m%dT%H%M%S")
logger.debug("Formatted timestamp for output file: %s" % (formatted_timestamp))
# instead of the number in the dither sequence,
# use the number of frames in this stack
number_of_frames = len(filelist)
# Assemble the entire filename
output_filename = "stack%s.%d__%s__%s.fits" % (
formatted_timestamp, number_of_frames, object_name, filter_name
)
output_filename = escape_characters(output_filename)
remote_output_filename = "%(outputdir)s/%(output_filename)s" % {
"outputdir": setup.output_dir,
"output_filename": output_filename,
}
logger.debug("Setting output filename: %s" % (output_filename))
#
# Re-format the input filelist to point to valid files
# on the remote filesystem
#
# Important: The input files specified are RAW files, but
# we need to stack based on the reduced files
#
remote_filelist = []
for fn in filelist:
remote_filename = format_filename(fn, setup.output_format)
remote_filelist.append(remote_filename)
#remote_filelist.append(setup.translate_filename_local2remote(fn))
logger.debug("Filelist on remote filesystem:\n%s" % ("".join([" --> %s\n" % fn for fn in remote_filelist])))
# "\n --> "+"\n --> ".join(remote_filelist)))
# If the non-sidereal option is set, use the tracking rate and
# configure the additional command-line flag for swarpstack
nonsidereal_option = ""
if (not tracking_rate == 'none'):
items = tracking_rate.split(",")
if (len(items) == 2):
track_ra = float(items[0])
track_dec = float(items[1])
if (track_ra != 0 or track_dec != 0):
# This fulfills all criteria for a valid non-sidereal command
# Use first frame as MJD reference frame
mjd_ref_frame = remote_filelist[0]
nonsidereal_option = "-nonsidereal=%(ra)s,%(dec)s,%(refframe)s" % {
'ra': items[0],
'dec': items[1],
'refframe': mjd_ref_frame,
}
logger.debug("Non-sidereal setup: %s" % (nonsidereal_option))
#
# Now we have the list of input files, and the output filename,
# lets go and initate the ssh request and get to work
#
# Set options (bgsub, pixelscale) etc.
options = "%s" % (nonsidereal_option)
if ("bgsub" in params and params['bgsub'] == 'yes'):
options += " -bgsub"
if ('pixelscale' in params):
try:
pixelscale = float(params['pixelscale'])
print("setting pixelscale")
if (pixelscale >= 0.1):
options += " -pixelscale=%s" % params['pixelscale']
except:
pass
if ('skipota' in params):
otas = params['skipota'].split(",")
ota_list = []
for ota in otas:
try:
ota_d = int(ota)
ota_list.append("%02d" % ota_d)
except:
pass
if (len(ota_list) > 0):
options += " -skipota=%s" % (",".join(ota_list))
# get the special swarp-settings command line
if (cmdline_arg_isset("-swarpopts")):
swarp_opts = cmdline_arg_set_or_default("-swarpopts", None)
# print "\n"*5,swarp_opts,"\n"*5
items = swarp_opts.split(":")
for item in items:
options += " -%s" % (item)
# Disabled for now, until we can properly handle different
# weight types to forward them to ds9
if ('combine' in params):
combine_mode = params['combine']
options += " -combine=%s" % (combine_mode.split(",")[0])
logger.info("Stacking %d frames, output in %s" % (len(filelist), output_filename))
# print "options=",options
ssh_command = "ssh %(username)s@%(host)s %(swarpnice)s \
%(podidir)s/podi_swarpstack.py \
%(remote_output_filename)s %(options)s %(remote_inputlist)s" % {
'username': setup.ssh_user,
'host': setup.ssh_host,
'swarpnice': setup.swarp_nicelevel,
'podidir': setup.remote_podi_dir,
'remote_output_filename': remote_output_filename,
'outputdir': setup.output_dir,
'output_filename': output_filename,
'options': options,
'remote_inputlist': " ".join(remote_filelist)
}
logger.debug("SSH command:\n%s" % (" ".join(ssh_command.split())))
#
# Now execute the actual swarpstack command
#
if (not cmdline_arg_isset("-dryrun")):
logger.info("Running swarpstack remotely on %s" % (setup.ssh_host))
start_time = time.time()
process = subprocess.Popen(ssh_command.split(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
_stdout, _stderr = process.communicate()
logger.info(str(_stdout))
# print _stdout
# print _stderr
end_time = time.time()
logger.info("swarpstack has completed successfully (%.2f seconds)" % (end_time - start_time))
else:
logger.info("Skipping execution (-dryrun given):\n\n%s\n\n" % (" ".join(ssh_command.split())))
#
# Once we are here, we have the output file created
# If requested, send it to ds9 to display
#
if (not cmdline_arg_isset("-dryrun") and
cmdline_arg_isset("-forward2ds9")):
local_filename = setup.translate_filename_remote2local(None, remote_output_filename)
# adjust the combine mode part of the filename
local_filename = local_filename[:-5]+".WEIGHTED.fits"
logger.debug("Commanding ds9 to display %s ..." % (local_filename))
cmd = "fits %s" % (local_filename)
try:
# print "\n"*5,"sending msg to ds9",local_filename,"\n"*5
cli_ds9 = sampy.SAMPIntegratedClient(metadata = metadata)
cli_ds9.connect()
cli_ds9.enotifyAll(mtype='ds9.set', cmd=cmd)
cli_ds9.disconnect()
logger.info("Sent command to display new stacked frame to ds9 (%s)" % (local_filename))
except:
logger.warning("Problems sending message to ds9")
pass
def workerprocess___qr_stack(queue):
#print "QR stacking worker process started, ready for action..."
logger = logging.getLogger("QRStacker")
logger.info("QR Stacking Listener started")
while (True):
try:
# print "\n\nWaiting for stuff to do\n\n"
task = queue.get()
except (KeyboardInterrupt, SystemExit) as e:
# print "worker received termination notice"
# Ignore the shut-down command here, and wait for the official
# shutdown command from main task
continue
if (task is None):
logger.info("Shutting down worker")
queue.task_done()
break
params = task
# print params
try:
handle_swarp_request(params, logger)
except:
podi_logging.log_exception()
pass
# Mark this task as done, this means we are ready for the next one.
queue.task_done()
continue
return
def handle_qr_stack_request(private_key, sender_id, msg_id, mtype, params, extra):
"""
This function is a callback handler that is called everytime a message
is received from the SAMP hub.
"""
logger = logging.getLogger("QRStackHandler")
# print "\n"*5
# print params
str_filelist = params['filelist']
tracking_rate = params['trackrate']
# print "adding timestamp"
params['timestamp'] = datetime.datetime.now()
# print "copying extras"
for key, value in extra.items():
params[key] = value
# print "adding to queue"
logger.info("Adding new stack-request to work queue")
stacking_queue.put(params)
# print "added msg to queue"
print("Done with this one, hungry for more!")
# print "\n"*5
return
#################################################################################
#
# end of swarpstack
#
#################################################################################
#################################################################################
#
#
# QR Mastercal functionality
#
# this uses the qr.mastercal message
#
#
#################################################################################
# define a message queue to handle remote executions
mastercals_queue = multiprocessing.JoinableQueue()
def handle_mastercals_request(params, logger, options):
# print "\n================"*3,params,"\n================"*3
str_filelist = params['filelist']
logger.debug("Received 'filelist': %s" % (str_filelist))
print(str_filelist)
# print "starting work on file",str_filelist
#
# Get rid of all files that do not exist
#
filelist = []
for fitsfile in str_filelist.split(","):
if (os.path.isfile(fitsfile)):
logger.debug("Found valid input file: %s" % (fitsfile))
filelist.append(fitsfile)
elif (os.path.isdir(fitsfile)):
logger.debug("Found directory name")
if (fitsfile[-1] == "/"):
fitsfile = fitsfile[:-1]
basedir, filebase = os.path.split(fitsfile)
fitsfile = "%s/%s.33.fits" % (fitsfile, filebase)
filelist.append(fitsfile)
# print "filelist = ",filelist
# We need at least one file to work on
if (len(filelist) <= 0):
logger.info("No valid files found to create MasterCalibrations!")
return
logger.info("Input filelist:\n%s" % ("\n".join([" --> %s" % fn for fn in filelist])))
# Find name of output directory
print(options['calib_dir'])
if (options['calib_dir'] == []):
# No cals directory given, this is no longer allowed!!!
logger.error("Need a -cals directory to support the make_calibrations mode")
return
#
# Just to be safe, translate the first -cals directory name from local to remote
#
remote_out_dirname = setup.translate_filename_local2remote(options['calib_dir'][0])
logger.info("Storing user-generated master calibration products in %s" % (
remote_out_dirname))
#
# Now translate the directory/filenames of all input files as well
#
filelist_remote = []
for fn in filelist:
filelist_remote.append(setup.translate_filename_local2remote(fn))
logger.info("Input files:\n-- %s" % ("\n-- ".join(filelist_remote)))
#
# Now we have the list of input files, and the output filename,
# lets go and initate the ssh request and get to work
#
qr_command = """
%(qrdir)s/podi_makecalibrations.py
from_cmdline
%(outdir)s
-nonlinearity
-redo
%(filelist)s
""" % {
"qrdir": setup.remote_podi_dir,
"outdir": remote_out_dirname,
"filelist": " ".join(filelist_remote),
}
logger.info("Executing\n\n\n%s\n" % (" ".join(qr_command.split())))
ssh_command = "ssh %(username)s@%(host)s %(qr_command)s" % {
'username': setup.ssh_user,
'host': setup.ssh_host,
'qr_command': qr_command,
}
logger.info("SSH command:\n%s" % (" ".join(ssh_command.split())))
#
# Now execute the actual swarpstack command
#
if (not cmdline_arg_isset("-dryrun")):
logger.info("Creating calibrations remotely on %s" % (setup.ssh_host))
start_time = time.time()
process = subprocess.Popen(ssh_command.split(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
_stdout, _stderr = process.communicate()
logger.debug(str(_stdout))
process.stdout.close()
process.stderr.close()
try:
process.terminate()
except:
pass
end_time = time.time()
logger.info("Master Calibrations completed successfully (%.2f seconds)" % (end_time - start_time))
else:
logger.info("Skipping execution (-dryrun given):\n\n%s\n\n" % (" ".join(ssh_command.split())))
return
def workerprocess___qr_mastercals(queue, options):
#print "QR MasterCals worker process started, ready for action..."
logger = logging.getLogger("QRMasterCals")
logger.info("MasterCal Listener started")
while (True):
try:
# print "\n\nWaiting for stuff to do\n\n"
task = queue.get()
except (KeyboardInterrupt, SystemExit) as e:
# print "worker received termination notice"
# Ignore the shut-down command here, and wait for the official
# shutdown command from main task
continue
if (task is None):
logger.info("Shutting down worker")
queue.task_done()
break
params = task
# print params
try:
handle_mastercals_request(params, logger, options)
except:
podi_logging.log_exception()
pass
# Mark this task as done, this means we are ready for the next one.
queue.task_done()
continue
return
def handle_qr_mastercals_request(private_key, sender_id, msg_id, mtype, params, extra):
"""
This function is a callback handler that is called everytime a message
is received from the SAMP hub.
"""
logger = logging.getLogger("QRMasterCalHandler")
# print "\n"*5
# print params
str_filelist = params['filelist']
#print params
#print str_filelist
# print "adding timestamp"
params['timestamp'] = datetime.datetime.now()
# print "copying extras"
for key, value in extra.iteritems():
params[key] = value
# print "adding to queue"
logger.info("Adding new mastercals-request to work queue")
mastercals_queue.put(params)
# print "added msg to queue"
logger.info("Done with this MasterCal request, hungry for more!")
# print "\n"*5
return
#################################################################################
#
# end of MasterCals
#
#################################################################################
def create_client(metadata, wait=0):
logger = logging.getLogger("ClientMgr")
# Create client, connect to Hub, and install message listener
cli1 = sampy.SAMPIntegratedClient(metadata = metadata)
try:
cli1.connect()
except sampy.SAMPHubError, sampy.SAMPClientError:
if (wait>0): time.sleep(wait)
return None
except :
logger.error("some other problem with connecting")
raise
try:
# Listen to all odi.image.file messages
cli1.bind_receive_message(setup.message_queue, receive_msg)
# Also define a new listener to listen to incoming qr.stack commands
cli1.bind_receive_message("qr.stack", handle_qr_stack_request)
# Also define a new listener to listen to incoming qr.stack commands
cli1.bind_receive_message("qr.mastercal", handle_qr_mastercals_request)
except Exception as err:
logger.error("Problem with bindReceiveMessage: %s" %err)
return cli1
def SAMPListener():
print("""
*******************************************************************
* SAMPListener for automatic image reduction (locally/remote) *
* Part of the QuickReduce package for the WIYN One Degree Imager *
* Author: Ralf Kotulla, kotulla@uwm.edu *
*******************************************************************
""")
logger = logging.getLogger("SAMPListener")
# Create a client
logger.info("Starting receiver ...")
logger.info("Trying to connect to Hub ...")
try:
while (True):
cli1 = create_client(metadata)
if (cli1 is None):
time.sleep(1)
else:
break
except (KeyboardInterrupt, SystemExit) as e:
logger.info("\rAborting and shutting down SAMPListener ...")
#sys.exit(0)
return
logger.info("Starting QR worker process...")
worker_process = multiprocessing.Process(target=worker_slave,
kwargs={
'queue': worker_queue,
}
)
worker_process.start()
#
# Also setup the QR stacking worker process
#
logger.info("Starting QR stacking process...")
qr_stacking_process = multiprocessing.Process(
target=workerprocess___qr_stack,
kwargs={
'queue': stacking_queue,
}
)
qr_stacking_process.start()
#
# Also setup the QR MasterCals worker process
#
logger.info("Starting QR MasterCal worker process...")
options = read_options_from_commandline(ignore_errors=True)
print(options)