-
Notifications
You must be signed in to change notification settings - Fork 1
/
FetchMetadata
executable file
·1051 lines (897 loc) · 35.2 KB
/
FetchMetadata
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/perl
#
# FetchMetadata
#
# Find the most current version at http://service.iris.edu/clients/
#
# Fetch metadata from a web service. The default web service is from
# the IRIS DMC, other FDSN web services may be specified by setting
# the following environment variables:
#
# SERVICEBASE = the base URI of the service(s) to use (http://service.iris.edu/)
# METADATAWS = complete URI of service (http://service.iris.edu/fdsnws/station/1)
#
# Dependencies: This script should run without problems on Perl
# release 5.10 or newer, older versions of Perl might require the
# installation of the following modules (and their dependencies):
# XML::SAX
# Bundle::LWP (libwww-perl)
#
# Installation of the XML::SAX::ExpatXS module can significantly
# speed up the parsing of metadata results returned as XML.
#
## Metadata selection
#
# Metadata is generally selected by specifying network, station,
# location, channel, start time and end time. The name parameters may
# contain wildcard characters. All input options are optional.
# Selections may be specified one of three ways:
#
# 1) Command line arguments: -N, -S, -L, -C, -Q, -s, -e
#
# 2) A BREQ_FAST formatted file, http://www.iris.edu/manuals/breq_fast.htm
#
# 3) A selection file containing a list of:
# Net Sta Loc Chan Start End
#
# Example selection file contents:
# II BFO 00 BHZ 2011-01-01T00:00:00 2011-01-01T01:00:00
# IU ANMO 00 BHZ 2011-01-01T00:00:00 2011-01-01T01:00:00
# IU COLA 00 BHZ 2011-01-01T00:00:00 2011-01-01T01:00:00
#
# For the command line arguments and the selection file the network,
# station location and channel fields may contain the common * and ?
# wildcards, meaning zero-to-many and a single character respectively.
# These fields may also be comma-separated lists, for example, the
# network may be specified as II,IU,TA to select three networks.
#
## Data output
#
# A line will be written to the file for each channel epoch and will
# contain:
# "net|sta|loc|chan|lat|lon|elev|depth|azimuth|dip|instrument|scale|scalefreq|scaleunits|samplerate|start|end"
#
# This metadata file can be used directly with mseed2sac or tracedsp
# to create SAC files including basic metadata.
#
#
# ## Change history ##
#
# 2010.217:
# - Initial version, split from FetchBulkData 2010.217
#
# 2010.273
# - Add -A option to specify an application name/version, this will be
# added to the UserAgent string.
#
# 2010.342
# - Convert metadata fetching to use the production ws-station service
# instead of the deprecated service previously used.
# - Rearrange and add fields to the metadata file output lines.
#
# 2011.020
# - Rework metadata parser for changed content (InstrumentSensitivity).
# - Add diagnostics and more graceful failure to metadata retrieval.
#
# 2011.046
# - Add -ua option to limit results to data updated after a date.
# - Save received XML metadata to a temporary file, the PurePerl SAX
# XML parser is much faster when working on files.
# - Allow comma-separated lists for selection by changing the delimiter
# for selection entries.
#
# 2011.089
# - Fix error message to report unrecognized channels in BREQ_FAST files.
#
# 2011.164
# - Add Perl and LWP version to UserAgent and wsclient URL to usage message.
# - Print script name and local time when verbose.
# - Add example of selection file and more comments on lists and wildcarding.
# - Add -msurl option to override metadata service query URL.
# - Add -sta option to request and parse station level information only
#
# 2011.172
# - Remove newline and carriage return characters and trailing spaces from
# site and instrument strings.
#
# 2011.337
# - Print error message text from service on errors.
# - Add undocumented -nobs option to prevent printing backspace characters in status.
# - Remove "query" portion from base URLs, moving them to the service calls.
# - Include local time in output of DONE line.
#
# 2012.045
# - Print "No data available" when return code is 204 in addition to 404.
# - Allow start/end times specified with microsecond resolution, subseconds are currently ignored.
# - Allow -- location IDs in BREQ_FAST formatted selections.
#
# 2012.061
# - Add -resp option to request response level information, no extra parsing
# or printing of response level details is included, useful for saving the XML.
# - Add index numbers to XML output file if more than one request is submitted
# to the server. Using a selection list or BREQ_FAST file for input can generate
# multiple requests, one request per line in fact.
#
# 2012.068:
# - Use new starttime and endtime parameters for ws-station instead of
# deprecated timewindow. These options can now be specified independently.
#
# 2012.100:
# - Parse site name in a new location of StationXML, site is now placed in the
# Site->Name element, was previously in the Site->Country element.
#
# 2012.102:
# - Correctly parse epoch times from channel epoch by skipping the new channel
# comment dates, this corrects the operating times in the metadata files.
#
# 2012.234:
# - Remove sorting, print data in order returned by the service.
# - Use vertical bars as field separators instead of commas, do not translate commas.
# - Do not convert dip to SAC convention, leave it in SEED convention.
#
# 2013.077:
# - Changed metadata parsing to understand FDSN StationXML schema.
# - Use the LWP::UserAgent method env_proxy() to check for and use connection
# proxy information from environment variables (e.g. http_proxy).
# - Add checking of environment variables that will override the web
# service base path (i.e. host name).
#
# 2013.186
# - Change service URL override command line options to match
# environment variables.
#
# 2013.197
# - Fix parsing of element values of "0".
#
# 2013.198
# - Add test for minimum version of LWP (libwww) module of 5.806.
#
# 2013.254
# - Allow validation of (virtual) network codes to contain a dash
# when parsing a BREQFAST file.
#
# 2014.056
# - Allow gzip'ed HTTP encoding for metadata requests if support
# exists on the local system.
#
# 2014.202
# - Exit with non-zero value on web service errors.
#
# 2014.316
# - Add -mts/-matchtimeseries option to turn submit the matchtimeseries
# parameter to the metadata service.
#
# 2015.007
# - Allow 1-3 character channel codes in breq_fast parsing, this allows
# single and double character strings with wildcards.
#
# Author: Chad Trabant, IRIS Data Management Center
use strict;
use File::Basename;
use Getopt::Long;
use LWP 5.806; # Require minimum version
use LWP::UserAgent;
use HTTP::Status qw(status_message);
use HTTP::Date;
use Time::HiRes;
my $version = "2015.007";
my $scriptname = basename($0);
# Default web service base
my $servicebase = 'http://service.iris.edu';
# Check for environment variable overrides for servicebase
$servicebase = $ENV{'SERVICEBASE'} if ( exists $ENV{'SERVICEBASE'} );
# Default web service for metadata
my $metadataservice = "$servicebase/fdsnws/station/1";
# Check for environment variable override for metadataservice
$metadataservice = $ENV{'METADATAWS'} if ( exists $ENV{'METADATAWS'} );
# HTTP UserAgent reported to web services
my $useragent = "$scriptname/$version Perl/$] " . new LWP::UserAgent->_agent;
my $usage = undef;
my $verbose = undef;
my $nobsprint = undef;
my $net = undef;
my $sta = undef;
my $loc = undef;
my $chan = undef;
my $starttime = undef;
my $endtime = undef;
my $updatedafter = undef;
my $matchtimeseries = undef;
my $selectfile = undef;
my $bfastfile = undef;
my $stalevel = undef;
my $resplevel = undef;
my $appname = undef;
my $auth = undef;
my $outfile = undef;
my $xmlfile = undef;
my $exitvalue = 0;
my $inflater = undef;
# If Compress::Raw::Zlib is available configure inflater for RFC 1952 (gzip)
if ( eval("use Compress::Raw::Zlib; 1") ) {
use Compress::Raw::Zlib;
$inflater = new Compress::Raw::Zlib::Inflate( -WindowBits => WANT_GZIP,
-ConsumeInput => 0 );
}
# Parse command line arguments
Getopt::Long::Configure ("bundling_override");
my $getoptsret = GetOptions ( 'help|usage|h' => \$usage,
'verbose|v+' => \$verbose,
'nobs' => \$nobsprint,
'net|N=s' => \$net,
'sta|S=s' => \$sta,
'loc|L=s' => \$loc,
'chan|C=s' => \$chan,
'starttime|s=s' => \$starttime,
'endtime|e=s' => \$endtime,
'updatedafter|ua=s' => \$updatedafter,
'matchtimeseries|mts' => \$matchtimeseries,
'selectfile|l=s' => \$selectfile,
'bfastfile|b=s' => \$bfastfile,
'stalevel|sta' => \$stalevel,
'resplevel|resp' => \$resplevel,
'appname|A=s' => \$appname,
'auth|a=s' => \$auth,
'outfile|o=s' => \$outfile,
'xmlfile|X=s' => \$xmlfile,
'metadataws=s' => \$metadataservice,
);
my $required = ( defined $net || defined $sta ||
defined $loc || defined $chan ||
defined $starttime || defined $endtime ||
defined $selectfile || defined $bfastfile );
if ( ! $getoptsret || $usage || ! $required ) {
print "$scriptname: collect channel metadata ($version)\n";
print "http://service.iris.edu/clients/\n\n";
print "Usage: $scriptname [options]\n\n";
print " Options:\n";
print " -v Increase verbosity, may be specified multiple times\n";
print " -N,--net Network code, list and wildcards (* and ?) accepted\n";
print " -S,--sta Station code, list and wildcards (* and ?) accepted\n";
print " -L,--loc Location ID, list and wildcards (* and ?) accepted\n";
print " -C,--chan Channel codes, list and wildcards (* and ?) accepted\n";
print " -s starttime Specify start time (YYYY-MM-DD,HH:MM:SS)\n";
print " -e endtime Specify end time (YYYY-MM-DD,HH:MM:SS)\n";
print " -ua date Limit to metadata updated after date (YYYY-MM-DD,HH:MM:SS)\n";
print " -mts Limit to metadata where criteria match time series data\n";
print " -X xmlfile Write raw returned FDSN StationXML to xmlfile\n";
print " -l listfile Read list of selections from file\n";
print " -b bfastfile Read list of selections from BREQ_FAST file\n";
print " -sta Print station level information, default is channel\n";
print " -resp Request response level information, no details printed\n";
print " -A appname Application/version string for identification\n";
print "\n";
print " -o outfile Write basic metadata to specified file instead of printing\n";
print "\n";
exit 1;
}
# Print script name and local time string
if ( $verbose ) {
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
printf STDERR "$scriptname ($version) at %4d-%02d-%02d %02d:%02d:%02d\n", $year+1900, $mon+1, $mday, $hour, $min, $sec;
}
# Normalize time strings
if ( $starttime ) {
my ($year,$month,$mday,$hour,$min,$sec,$subsec) = split (/[-:,.\s\/T]/, $starttime);
$starttime = sprintf ("%04d-%02d-%02dT%02d:%02d:%02d", $year, $month, $mday, $hour, $min, $sec);
$starttime .= ".$subsec" if ( $subsec );
}
if ( $endtime ) {
my ($year,$month,$mday,$hour,$min,$sec,$subsec) = split (/[-:,.\s\/T]/, $endtime);
$endtime = sprintf ("%04d-%02d-%02dT%02d:%02d:%02d", $year, $month, $mday, $hour, $min, $sec);
$endtime .= ".$subsec" if ( $subsec );
}
if ( $updatedafter ) {
my ($year,$month,$mday,$hour,$min,$sec,$subsec) = split (/[-:,.\s\/T]/, $updatedafter);
$updatedafter = sprintf ("%04d-%02d-%02dT%02d:%02d:%02d", $year, $month, $mday, $hour, $min, $sec);
$updatedafter .= ".$subsec" if ( $subsec );
}
# An array to hold data selections
my @selections = ();
# Add command line selection to list
if ( defined $net || defined $sta || defined $loc || defined $chan ||
defined $starttime || defined $endtime ) {
push (@selections,"$net|$sta|$loc|$chan|$starttime|$endtime");
}
# Read selection list file
if ( $selectfile ) {
print STDERR "Reading data selection from list file '$selectfile'\n";
&ReadSelectFile ($selectfile);
}
# Read BREQ_FAST file
if ( $bfastfile ) {
print STDERR "Reading data selection from BREQ_FAST file '$bfastfile'\n";
&ReadBFastFile ($bfastfile);
}
# Report complete data selections
if ( $verbose > 2 ) {
print STDERR "== Data selections ==\n";
foreach my $select ( @selections ) {
print STDERR " $select\n";
}
}
# An array to hold channel list and metadata
my @metadata = ();
my $metadataxml;
my $datasize;
# Fetch metadata from the station web service
my $selectidx = 0;
foreach my $selection ( @selections ) {
my ($snet,$ssta,$sloc,$schan,$sstart,$send) = split (/\|/,$selection);
&FetchMetaData($snet,$ssta,$sloc,$schan,$sstart,$send);
$selectidx++;
}
# Write to either specified output file or stdout
my $metafile = ( $outfile ) ? $outfile : "-";
# Write metadata to file
if ( $metafile ) {
if ( scalar @metadata <= 0 ) {
printf STDERR "No metdata available\n", scalar @metadata;
}
elsif ( ! defined $stalevel ) {
printf STDERR "Writing metadata (%d channel epochs) file\n", scalar @metadata if ( $verbose );
open (META, ">$metafile") || die "Cannot open metadata file '$metafile': $!\n";
# Print header line
print META "#net|sta|loc|chan|lat|lon|elev|depth|azimuth|dip|instrument|scale|scalefreq|scaleunits|samplerate|start|end\n";
foreach my $channel ( @metadata ) {
my ($net,$sta,$loc,$chan,$start,$end,$lat,$lon,$elev,$depth,$azimuth,$dip,$instrument,$samplerate,$sens,$sensfreq,$sensunit) =
split (/\|/, $channel);
$sensfreq = sprintf ("%0g", $sensfreq);
$samplerate = sprintf ("%0g", $samplerate);
print META "$net|$sta|$loc|$chan|$lat|$lon|$elev|$depth|$azimuth|$dip|$instrument|$sens|$sensfreq|$sensunit|$samplerate|$start|$end\n";
}
close META;
}
else {
printf STDERR "Writing metadata (%d station epochs) file\n", scalar @metadata if ( $verbose );
open (META, ">$metafile") || die "Cannot open metadata file '$metafile': $!\n";
# Print header line
print META "#net|sta|lat|lon|elev|site|start|end\n";
foreach my $station ( @metadata ) {
my ($net,$sta,$start,$end,$lat,$lon,$elev,$site) = split (/\|/, $station);
print META "$net|$sta|$lat|$lon|$elev|$site|$start|$end\n";
}
close META;
}
}
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
printf STDERR "DONE at %4d-%02d-%02d %02d:%02d:%02d\n", $year+1900, $mon+1, $mday, $hour, $min, $sec;
exit $exitvalue;
## End of main
######################################################################
# ReadSelectFile:
#
# Read selection list file and add entries to the @selections array.
#
# Selection lines are expected to be in the following form:
#
# "Net Sta Loc Chan Start End"
#
# The Net, Sta, Loc and Channel fields are required and can be
# specified as wildcards.
######################################################################
sub ReadSelectFile {
my $selectfile = shift;
open (SF, "<$selectfile") || die "Cannot open '$selectfile': $!\n";
foreach my $line ( <SF> ) {
chomp $line;
next if ( $line =~ /^\#/ ); # Skip comment lines
my ($net,$sta,$loc,$chan,$start,$end) = split (' ', $line);
next if ( ! defined $chan );
# Normalize time strings
if ( $start ) {
my ($year,$month,$mday,$hour,$min,$sec,$subsec) = split (/[-:,.\s\/T]/, $start);
$start = sprintf ("%04d-%02d-%02dT%02d:%02d:%02d", $year, $month, $mday, $hour, $min, $sec);
$start .= ".$subsec" if ( $subsec );
}
if ( $end ) {
my ($year,$month,$mday,$hour,$min,$sec,$subsec) = split (/[-:,.\s\/T]/, $end);
$end = sprintf ("%04d-%02d-%02dT%02d:%02d:%02d", $year, $month, $mday, $hour, $min, $sec);
$end .= ".$subsec" if ( $subsec );
}
# Add selection to global list
push (@selections,"$net|$sta|$loc|$chan|$start|$end");
}
close SF;
} # End of ReadSelectFile()
######################################################################
# ReadBFastFile:
#
# Read BREQ_FAST file and add entries to the @selections array.
#
######################################################################
sub ReadBFastFile {
my $bfastfile = shift;
open (BF, "<$bfastfile") || die "Cannot open '$bfastfile': $!\n";
my $linecount = 0;
BFLINE: foreach my $line ( <BF> ) {
chomp $line;
$linecount++;
next if ( ! $line ); # Skip empty lines
next if ( $line =~ /^\./ ); # Skip other header lines
my ($sta,$net,$syear,$smon,$sday,$shour,$smin,$ssec,$eyear,$emon,$eday,$ehour,$emin,$esec,$count,@chans) = split (' ', $line);
# Simple validation of BREQ FAST fields
if ( $sta !~ /^[A-Za-z0-9*?]{1,5}$/ ) {
print "Unrecognized station code: '$sta', skipping line $linecount\n" if ( $verbose );
next;
}
if ( $net !~ /^[-_A-Za-z0-9*?]+$/ ) {
print "Unrecognized network code: '$net', skipping line $linecount\n" if ( $verbose );
next;
}
if ( $syear !~ /^\d\d\d\d$/ ) {
print "Unrecognized start year: '$syear', skipping line $linecount\n" if ( $verbose );
next;
}
if ( $smon !~ /^\d{1,2}$/ ) {
print "Unrecognized start month: '$smon', skipping line $linecount\n" if ( $verbose );
next;
}
if ( $sday !~ /^\d{1,2}$/ ) {
print "Unrecognized start day: '$sday', skipping line $linecount\n" if ( $verbose );
next;
}
if ( $shour !~ /^\d{1,2}$/ ) {
print "Unrecognized start hour: '$shour', skipping line $linecount\n" if ( $verbose );
next;
}
if ( $smin !~ /^\d{1,2}$/ ) {
print "Unrecognized start min: '$smin', skipping line $linecount\n" if ( $verbose );
next;
}
if ( $ssec !~ /^\d{1,2}\.?\d{0,6}?$/ ) {
print "Unrecognized start seconds: '$ssec', skipping line $linecount\n" if ( $verbose );
next;
}
if ( $eyear !~ /^\d\d\d\d$/ ) {
print "Unrecognized end year: '$eyear', skipping line $linecount\n" if ( $verbose );
next;
}
if ( $emon !~ /^\d{1,2}$/ ) {
print "Unrecognized end month: '$emon', skipping line $linecount\n" if ( $verbose );
next;
}
if ( $eday !~ /^\d{1,2}$/ ) {
print "Unrecognized end day: '$eday', skipping line $linecount\n" if ( $verbose );
next;
}
if ( $ehour !~ /^\d{1,2}$/ ) {
print "Unrecognized end hour: '$ehour', skipping line $linecount\n" if ( $verbose );
next;
}
if ( $emin !~ /^\d{1,2}$/ ) {
print "Unrecognized end min: '$emin', skipping line $linecount\n" if ( $verbose );
next;
}
if ( $esec !~ /^\d{1,2}\.?\d{0,6}?$/ ) {
print "Unrecognized end seconds: '$esec', skipping line $linecount\n" if ( $verbose );
next;
}
if ( $count !~ /^\d+$/ || $count <= 0 ) {
print "Invalid channel count field: '$count', skipping line $linecount\n" if ( $verbose );
next;
}
if ( scalar @chans <= 0 ) {
print "No channels specified, skipping line $linecount\n" if ( $verbose );
next;
}
# Extract location ID if present, i.e. if channel count is one less than present
my $loc = undef;
$loc = pop @chans if ( scalar @chans == ($count+1) );
if ( $loc && $loc !~ /^[A-Za-z0-9*?\-]{1,2}$/ ) {
print "Unrecognized location ID: '$loc', skipping line $linecount\n" if ( $verbose );
next;
}
foreach my $chan ( @chans ) {
if ( $chan !~ /^[A-Za-z0-9*?]{1,3}$/ ) {
print "Unrecognized channel codes: '$chan', skipping line $linecount\n" if ( $verbose );
next BFLINE;
}
}
if ( scalar @chans != $count ) {
printf "Channel count field ($count) does not match number of channels specified (%d), skipping line $linecount\n",
scalar @chans if ( $verbose );
next;
}
# Normalize time strings
my ($ssec,$ssub) = split (/\./, $ssec);
my $start = sprintf ("%04d-%02d-%02dT%02d:%02d:%02d", $syear, $smon, $sday, $shour, $smin, $ssec);
$start .= ".$ssub" if ( $ssub );
my ($esec,$esub) = split (/\./, $esec);
my $end = sprintf ("%04d-%02d-%02dT%02d:%02d:%02d", $eyear, $emon, $eday, $ehour, $emin, $esec);
$end .= ".$esub" if ( $esub );
# Add selection to global list for each channel
foreach my $chan ( @chans ) {
push (@selections,"$net|$sta|$loc|$chan|$start|$end");
}
}
close BF;
} # End of ReadBFastFile()
######################################################################
# FetchMetaData:
#
# Collect metadata and expand wildcards for selected data set.
#
# Resulting metadata is placed in the global @metadata array with each
# entry taking the following form:
# "net|sta|loc|chan|start|end|lat|lon|elev|depth|azimuth|dip|instrument|samplerate|sensitivity|sensfreq|sensunits"
#
######################################################################
sub FetchMetaData {
my ($rnet,$rsta,$rloc,$rchan,$rstart,$rend) = @_;
# Create HTTP user agent
my $ua = RequestAgent->new();
$ua->env_proxy;
my $level = "channel";
$level = "station" if ( $stalevel );
$level = "response" if ( $resplevel );
# Create web service URI
my $uri = "${metadataservice}/query?level=$level";
$uri .= "&network=$rnet" if ( $rnet );
$uri .= "&station=$rsta" if ( $rsta );
$uri .= "&location=$rloc" if ( $rloc );
$uri .= "&channel=$rchan" if ( $rchan );
$uri .= "&starttime=$rstart" if ( $rstart );
$uri .= "&endtime=$rend" if ( $rend );
$uri .= "&updatedafter=$updatedafter" if ( $updatedafter );
$uri .= "&matchtimeseries=TRUE" if ( $matchtimeseries );
my $ftime = Time::HiRes::time;
print STDERR "Metadata URI: '$uri'\n" if ( $verbose > 1 );
print STDERR "Fetching metadata :: " if ( $verbose );
$datasize = 0;
$metadataxml = "";
# Fetch metadata from web service using callback routine
my $response = ( $inflater ) ?
$ua->get($uri, 'Accept-Encoding' => 'gzip', ':content_cb' => \&MDCallBack ) :
$ua->get($uri, ':content_cb' => \&MDCallBack );
$inflater->inflateReset if ( $inflater );
if ( $response->code == 204 ) {
print (STDERR "No data available\n") if ( $verbose );
return;
}
elsif ( ! $response->is_success() ) {
print (STDERR "Error fetching data: "
. $response->code . " :: " . status_message($response->code) . "\n");
print STDERR "------\n" . $response->decoded_content . "\n------\n";
print STDERR " URI: '$uri'\n" if ( $verbose > 1 );
$exitvalue = 1;
}
else {
printf (STDERR "%s\n", ($nobsprint)?sizestring($datasize):"") if ( $verbose );
}
my $duration = Time::HiRes::time - $ftime;
my $rate = $datasize/(($duration)?$duration:0.000001);
printf (STDERR "Received %s of metadata in %.1f seconds (%s/s)\n",
sizestring($datasize), $duration, sizestring($rate));
# Return if no metadata received
return if ( length $metadataxml <= 0 );
# Create stream oriented XML parser instance
use XML::SAX;
my $parser = undef;
if ( ! defined $stalevel ) {
$parser = new XML::SAX::ParserFactory->parser( Handler => MDSHandlerChannel->new );
}
else {
$parser = new XML::SAX::ParserFactory->parser( Handler => MDSHandlerStation->new );
}
my $totalepochs = 0;
my $ptime = Time::HiRes::time;
print STDERR "Parsing XML metadata... " if ( $verbose );
# Open file to store metadata XML
my $xmlfileidx = ( $selectidx ) ? "$xmlfile.$selectidx" : $xmlfile; # Make separate files for each request
my $metadataxmlfile = ( $xmlfile ) ? $xmlfileidx : "metadata-$$.xml";
if ( open (MXML, ">$metadataxmlfile") ) {
# Write XML and close file
print MXML $metadataxml;
close MXML;
# Parse XML metadata from file
$parser->parse_file ($metadataxmlfile);
# Remove temporary XML metadata file
if ( ! defined $xmlfile ) {
if ( ! unlink $metadataxmlfile ) {
print STDERR "Cannot remove temporary XML metadata file: $!\n";
}
}
}
# Otherwise parse the XML in memory
else {
printf STDERR " in memory (possibly slow), " if ( $verbose );
# Parse XML metadata from string
$parser->parse_string ($metadataxml);
}
printf STDERR "Done (%.1f seconds)\n", Time::HiRes::time - $ptime if ( $verbose );
my $duration = Time::HiRes::time - $ftime;
my $rate = $datasize/(($duration)?$duration:0.000001);
printf (STDERR "Processed metadata for $totalepochs %s epochs in %.1f seconds (%s/s)\n",
($stalevel)?"station":"channel",$duration, sizestring($rate));
## End of this routine, below is the XML parsing handlers used above
## Beginning of SAX MDSHandlerChannel, event-based streaming XML parsing for Channel level FDSN StationXML
package MDSHandlerChannel;
use base qw(XML::SAX::Base);
use HTTP::Date;
my $inchannel = 0;
my $inlat = 0;
my $inlon = 0;
my $inelevation = 0;
my $indepth = 0;
my $inazimuth = 0;
my $indip = 0;
my $insensor = 0;
my $insensortype = 0;
my $insamplerate = 0;
my $ininstsens = 0;
my $insensvalue = 0;
my $insensfreq = 0;
my $ininputunits = 0;
my $inunitname = 0;
my ($net,$sta,$loc,$chan,$start,$end,$lat,$lon,$elev,$depth,$azimuth,$dip,$instrument,$samplerate,$sens,$sensfreq,$sensunit) = (undef) x 17;
sub start_element {
my ($self,$element) = @_;
if ( $element->{Name} eq "Network" ) {
$net = $element->{Attributes}->{'{}code'}->{Value};
}
elsif ( $element->{Name} eq "Station" ) {
($sta,$loc,$chan,$start,$end,$lat,$lon,$elev,$depth,$azimuth,$dip,$instrument,$samplerate,$sens,$sensfreq,$sensunit) = (undef) x 16;
$sta = $element->{Attributes}->{'{}code'}->{Value};
}
elsif ( $element->{Name} eq "Channel" ) {
$loc = $element->{Attributes}->{'{}locationCode'}->{Value};
$chan = $element->{Attributes}->{'{}code'}->{Value};
$start = $element->{Attributes}->{'{}startDate'}->{Value};
$end = $element->{Attributes}->{'{}endDate'}->{Value};
$inchannel = 1;
}
if ( $inchannel ) {
if ( $element->{Name} eq "Latitude" ) { $inlat = 1; }
elsif ( $element->{Name} eq "Longitude" ) { $inlon = 1; }
elsif ( $element->{Name} eq "Elevation" ) { $inelevation = 1; }
elsif ( $element->{Name} eq "Depth" ) { $indepth = 1; }
elsif ( $element->{Name} eq "Azimuth" ) { $inazimuth = 1; }
elsif ( $element->{Name} eq "Dip" ) { $indip = 1; }
elsif ( $element->{Name} eq "SampleRate" ) { $insamplerate = 1; }
elsif ( $element->{Name} eq "Sensor" ) { $insensor = 1; }
elsif ( $element->{Name} eq "InstrumentSensitivity" ) { $ininstsens = 1; }
}
if ( $insensor ) {
if ( $element->{Name} eq "Type" ) { $insensortype = 1; }
}
if ( $ininstsens ) {
if ( $element->{Name} eq "Value" ) { $insensvalue = 1; }
elsif ( $element->{Name} eq "Frequency" ) { $insensfreq = 1; }
elsif ( $element->{Name} eq "InputUnits" ) { $ininputunits = 1; }
}
if ( $ininputunits ) {
if ( $element->{Name} eq "Name" ) { $inunitname = 1; }
}
}
sub end_element {
my ($self,$element) = @_;
if ( $element->{Name} eq "Network" ) {
$net = 0;
}
elsif ( $element->{Name} eq "Station" ) {
$sta = 0;
}
elsif ( $element->{Name} eq "Channel" ) {
# Track epoch count
$totalepochs++;
# Translate metadata location ID to "--" if it's spaces
my $dloc = ( $loc eq " " ) ? "--" : $loc;
# Remove newlines, returns & trailing spaces in metadata instrument name
$instrument =~ s/[\n\r]//g;
$instrument =~ s/\s*$//g;
# Cleanup start and end strings
($start) = $start =~ /^(\d{4,4}[-\/,:]\d{1,2}[-\/,:]\d{1,2}[-\/,:T]\d{1,2}[-\/,:]\d{1,2}[-\/,:]\d{1,2}).*/;
($end) = $end =~ /^(\d{4,4}[-\/,:]\d{1,2}[-\/,:]\d{1,2}[-\/,:T]\d{1,2}[-\/,:]\d{1,2}[-\/,:]\d{1,2}).*/;
# Push channel epoch metadata into storage array
push (@metadata, "$net|$sta|$dloc|$chan|$start|$end|$lat|$lon|$elev|$depth|$azimuth|$dip|$instrument|$samplerate|$sens|$sensfreq|$sensunit");
# Reset Epoch level fields
($loc,$chan,$start,$end,$lat,$lon,$elev,$depth,$azimuth,$dip,$instrument,$samplerate,$sens,$sensfreq,$sensunit) = (undef) x 15;
$inchannel = 0;
}
if ( $inchannel ) {
if ( $element->{Name} eq "Latitude" ) { $inlat = 0; }
elsif ( $element->{Name} eq "Longitude" ) { $inlon = 0; }
elsif ( $element->{Name} eq "Elevation" ) { $inelevation = 0; }
elsif ( $element->{Name} eq "Depth" ) { $indepth = 0; }
elsif ( $element->{Name} eq "Azimuth" ) { $inazimuth = 0; }
elsif ( $element->{Name} eq "Dip" ) { $indip = 0; }
elsif ( $element->{Name} eq "SampleRate" ) { $insamplerate = 0; }
elsif ( $element->{Name} eq "Sensor" ) { $insensor = 0; }
elsif ( $element->{Name} eq "InstrumentSensitivity" ) { $ininstsens = 0; }
}
if ( $insensor ) {
if ( $element->{Name} eq "Type" ) { $insensortype = 0; }
}
if ( $ininstsens ) {
if ( $element->{Name} eq "Value" ) { $insensvalue = 0; }
elsif ( $element->{Name} eq "Frequency" ) { $insensfreq = 0; }
elsif ( $element->{Name} eq "InputUnits" ) { $ininputunits = 0; }
}
if ( $ininputunits ) {
if ( $element->{Name} eq "Name" ) { $inunitname = 0; }
}
}
sub characters {
my ($self,$element) = @_;
if ( defined $element->{Data} ) {
if ( $inlat ) { $lat .= $element->{Data}; }
elsif ( $inlon ) { $lon .= $element->{Data}; }
elsif ( $inelevation ) { $elev .= $element->{Data}; }
elsif ( $indepth ) { $depth .= $element->{Data}; }
elsif ( $inazimuth ) { $azimuth .= $element->{Data}; }
elsif ( $indip ) { $dip .= $element->{Data}; }
elsif ( $insamplerate ) { $samplerate .= $element->{Data}; }
elsif ( $insensortype ) { $instrument .= $element->{Data}; }
elsif ( $insensvalue ) { $sens .= $element->{Data}; }
elsif ( $insensfreq ) { $sensfreq .= $element->{Data}; }
elsif ( $inunitname ) { $sensunit .= $element->{Data}; }
}
} # End of SAX MDSHandlerChannel
## Beginning of SAX MDSHandlerStation, event-based streaming XML parsing for Station level FDSN StationXML
package MDSHandlerStation;
use base qw(XML::SAX::Base);
use HTTP::Date;
my $instation = 0;
my $inlat = 0;
my $inlon = 0;
my $inelevation = 0;
my $insite = 0;
my $inname = 0;
my ($net,$sta,$start,$end,$lat,$lon,$elev,$site) = (undef) x 8;
sub start_element {
my ($self,$element) = @_;
if ( $element->{Name} eq "Network" ) {
$net = $element->{Attributes}->{'{}code'}->{Value};
}
elsif ( $element->{Name} eq "Station" ) {
($sta,$start,$end,$lat,$lon,$elev,$site) = (undef) x 7;
$sta = $element->{Attributes}->{'{}code'}->{Value};
$start = $element->{Attributes}->{'{}startDate'}->{Value};
$end = $element->{Attributes}->{'{}endDate'}->{Value};
$instation = 1;
}
if ( $instation ) {
if ( $element->{Name} eq "Latitude" ) { $inlat = 1; }
elsif ( $element->{Name} eq "Longitude" ) { $inlon = 1; }
elsif ( $element->{Name} eq "Elevation" ) { $inelevation = 1; }
elsif ( $element->{Name} eq "Site" ) { $insite = 1; }
}
if ( $insite ) {
if ( $element->{Name} eq "Name" ) { $inname = 1; }
}
}
sub end_element {
my ($self,$element) = @_;
if ( $element->{Name} eq "Network" ) {
$net = 0;
}
elsif ( $element->{Name} eq "Station" ) {
# Track epoch count
$totalepochs++;
# Remove newlines, returns and trailing spaces in site name
$site =~ s/[\n\r]//g;
$site =~ s/\s*$//g;
# Cleanup start and end strings
($start) = $start =~ /^(\d{4,4}[-\/,:]\d{1,2}[-\/,:]\d{1,2}[-\/,:T]\d{1,2}[-\/,:]\d{1,2}[-\/,:]\d{1,2}).*/;
($end) = $end =~ /^(\d{4,4}[-\/,:]\d{1,2}[-\/,:]\d{1,2}[-\/,:T]\d{1,2}[-\/,:]\d{1,2}[-\/,:]\d{1,2}).*/;
# Push channel epoch metadata into storage array
push (@metadata, "$net|$sta|$start|$end|$lat|$lon|$elev|$site");
# Reset StationEpoch level fields
($sta,$start,$end,$lat,$lon,$elev,$site) = (undef) x 7;
$instation = 0;
}
if ( $instation ) {
if ( $element->{Name} eq "Latitude" ) { $inlat = 0; }
elsif ( $element->{Name} eq "Longitude" ) { $inlon = 0; }
elsif ( $element->{Name} eq "Elevation" ) { $inelevation = 0; }
elsif ( $element->{Name} eq "Site" ) { $insite = 0; }
}
if ( $insite ) {
if ( $element->{Name} eq "Name" ) { $inname = 0; }
}
}
sub characters {
my ($self,$element) = @_;
if ( defined $element->{Data} ) {
if ( $inlat ) { $lat .= $element->{Data}; }
elsif ( $inlon ) { $lon .= $element->{Data}; }
elsif ( $inelevation ) { $elev .= $element->{Data}; }
elsif ( $inname ) { $site .= $element->{Data}; }
}
} # End of SAX MDSHandlerStation
} # End of FetchMetaData()
######################################################################
# MDCallBack:
#
# A call back for LWP downloading of metadata.
#
# Add received data to metadataxml string, tally up the received data
# size and print and updated (overwriting) byte count string.
######################################################################
sub MDCallBack {
my ($data, $response, $protocol) = @_;
$datasize += length($data);
if ( $response->content_encoding() =~ /gzip/ ) {
my $datablock = "";
$inflater->inflate($data, $datablock);
$metadataxml .= $datablock;
}
else {
$metadataxml .= $data;
}
if ( $verbose && ! $nobsprint ) {
printf (STDERR "%-10.10s\b\b\b\b\b\b\b\b\b\b", sizestring($datasize));
}
}
######################################################################
# sizestring (bytes):
#
# Return a clean size string for a given byte count.
######################################################################
sub sizestring { # sizestring (bytes)
my $bytes = shift;
if ( $bytes < 1000 ) {
return sprintf "%d Bytes", $bytes;
}
elsif ( ($bytes / 1024) < 1000 ) {
return sprintf "%.1f KB", $bytes / 1024;
}
elsif ( ($bytes / 1024 / 1024) < 1000 ) {
return sprintf "%.1f MB", $bytes / 1024 / 1024;
}
elsif ( ($bytes / 1024 / 1024 / 1024) < 1000 ) {
return sprintf "%.1f GB", $bytes / 1024 / 1024 / 1024;
}
elsif ( ($bytes / 1024 / 1024 / 1024 / 1024) < 1000 ) {
return sprintf "%.1f TB", $bytes / 1024 / 1024 / 1024 / 1024;
}
else {
return "";
}