Debian Codegraph @

eutils/cache.go

raw
1 // ===========================================================================
2 //
3 // PUBLIC DOMAIN NOTICE
4 // National Center for Biotechnology Information (NCBI)
5 //
6 // This software/database is a "United States Government Work" under the
7 // terms of the United States Copyright Act. It was written as part of
8 // the author's official duties as a United States Government employee and
9 // thus cannot be copyrighted. This software/database is freely available
10 // to the public for use. The National Library of Medicine and the U.S.
11 // Government do not place any restriction on its use or reproduction.
12 // We would, however, appreciate having the NCBI and the author cited in
13 // any work or product based on this material.
14 //
15 // Although all reasonable efforts have been taken to ensure the accuracy
16 // and reliability of the software and data, the NLM and the U.S.
17 // Government do not and cannot warrant the performance or results that
18 // may be obtained by using this software or data. The NLM and the U.S.
19 // Government disclaim all warranties, express or implied, including
20 // warranties of performance, merchantability or fitness for any particular
21 // purpose.
22 //
23 // ===========================================================================
24 //
25 // File Name: cache.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "bufio"
35 "bytes"
36 "compress/gzip"
37 "fmt"
38 "hash/crc32"
39 "io"
40 "os"
41 "path/filepath"
42 "runtime"
43 "strconv"
44 "strings"
45 "sync"
46 "time"
47 )
48
49 // fetchOneXMLRecord is an internal function for fetching an XML record from the archive
50 func fetchOneXMLRecord(id, base, pfx, sfx string, zipp bool, buf bytes.Buffer) string {
51
52 if id == "" {
53 return ""
54 }
55
56 id = strings.TrimPrefix(id, "PMC")
57
58 dir, file := ArchiveTrie(id)
59
60 if dir == "" || file == "" {
61 return ""
62 }
63
64 if zipp {
65 sfx += ".gz"
66 }
67
68 fpath := filepath.Join(base, dir, pfx+file+sfx)
69 if fpath == "" {
70 return ""
71 }
72
73 iszip := zipp
74
75 inFile, err := os.Open(fpath)
76
77 // if failed to find ".xml" or ".e2x" file, try ".xml.gz" or ".e2x.gz" without requiring -gzip
78 if err != nil && os.IsNotExist(err) && !zipp {
79 iszip = true
80 fpath := filepath.Join(base, dir, pfx+file+sfx+".gz")
81 if fpath == "" {
82 return ""
83 }
84 inFile, err = os.Open(fpath)
85 }
86 if err != nil {
87 msg := err.Error()
88 if !strings.HasSuffix(msg, "no such file or directory") && !strings.HasSuffix(msg, "cannot find the path specified.") {
89 fmt.Fprintf(os.Stderr, "%s\n", msg)
90 }
91 return ""
92 }
93
94 defer inFile.Close()
95
96 brd := bufio.NewReader(inFile)
97
98 if iszip {
99
100 zpr, err := gzip.NewReader(brd)
101
102 defer zpr.Close()
103
104 if err == nil {
105 // copy and decompress cached file contents
106 buf.ReadFrom(zpr)
107 }
108
109 } else {
110
111 // copy cached file contents
112 buf.ReadFrom(brd)
113 }
114
115 str := buf.String()
116
117 return str
118 }
119
120 // FetchLocalRecord returns the XML for a single UID
121 func FetchLocalRecord(id, db, pfx, ptrn string) string {
122
123 if id == "" || db == "" {
124 return ""
125 }
126
127 if pfx != "" {
128 id = strings.TrimPrefix(id, pfx)
129 }
130
131 var buf bytes.Buffer
132
133 // obtain path from environment variable
134 archiveBase := GetLocalArchiveFolder(db, "Archive", true)
135
136 if archiveBase == "" {
137 DisplayError("Unable to get local archive path")
138 os.Exit(1)
139 }
140
141 // check to make sure local archive is mounted
142 _, err := os.Stat(archiveBase)
143 if err != nil && os.IsNotExist(err) {
144 DisplayError("Local archive and search index is not mounted")
145 os.Exit(1)
146 }
147
148 str := fetchOneXMLRecord(id, archiveBase, pfx, ".xml", true, buf)
149
150 // trim any header included in archive XML file
151 if str != "" && ptrn != "" {
152 pos := strings.Index(str, "<"+ptrn+">")
153 if pos > 0 {
154 // remove any leading xml and DOCTYPE lines
155 str = str[pos:]
156 }
157 }
158
159 return str
160 }
161
162 // GzipString allows separate compression of xml + DOCTYPE header and PubmedArticle record
163 func GzipString(str string) []byte {
164
165 if str == "" {
166 return nil
167 }
168
169 var buf bytes.Buffer
170
171 // for small files, use regular gzip
172 gzWriter, err := gzip.NewWriterLevel(&buf, gzip.DefaultCompression)
173 if err != nil {
174 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
175 return nil
176 }
177
178 gzWriter.Write([]byte(str))
179 gzWriter.Close()
180
181 return buf.Bytes()
182 }
183
184 // CreateUIDReader sends PMIDs and their numeric orders down a channel.
185 // This allows detection of updated records that appear shortly after
186 // earlier versions, preventing the wrong version from being saved.
187 func CreateUIDReader(in io.Reader) <-chan XMLRecord {
188
189 if in == nil {
190 return nil
191 }
192
193 out := make(chan XMLRecord, chanDepth)
194 if out == nil {
195 DisplayError("Unable to create uid reader channel")
196 os.Exit(1)
197 }
198
199 // uidReader reads uids from input stream and sends through channel
200 uidReader := func(in io.Reader, out chan<- XMLRecord) {
201
202 // close channel when all records have been processed
203 defer close(out)
204
205 scanr := bufio.NewScanner(in)
206
207 idx := 0
208 for scanr.Scan() {
209
210 // read lines of identifiers
211 file := scanr.Text()
212 idx++
213
214 pos := strings.Index(file, ".")
215 if pos >= 0 {
216 // remove version suffix
217 file = file[:pos]
218 }
219
220 out <- XMLRecord{Index: idx, Text: file}
221 }
222 }
223
224 // launch single uid reader goroutine
225 go uidReader(in, out)
226
227 return out
228 }
229
230 // ReadsUIDsFromString reads a comma-separated string of uids and sends through channel
231 func ReadsUIDsFromString(uids string) <-chan XMLRecord {
232
233 if uids == "" {
234 return nil
235 }
236
237 out := make(chan XMLRecord, chanDepth)
238 if out == nil {
239 DisplayError("Unable to create uid string reader channel")
240 os.Exit(1)
241 }
242
243 // uidStringReader reads uids from input stream and sends through channel
244 uidStringReader := func(uids string, out chan<- XMLRecord) {
245
246 // close channel when all records have been processed
247 defer close(out)
248
249 items := strings.Split(uids, ",")
250
251 idx := 0
252 for _, item := range items {
253
254 idx++
255
256 pos := strings.Index(item, ".")
257 if pos >= 0 {
258 // remove version suffix
259 item = item[:pos]
260 }
261
262 out <- XMLRecord{Index: idx, Text: item}
263 }
264 }
265
266 // launch single uid string reader goroutine
267 go uidStringReader(uids, out)
268
269 return out
270 }
271
272 func mapXMLtoASN(node *XMLNode, proc func(string)) {
273
274 if node == nil || proc == nil {
275 return
276 }
277
278 // array to speed up indentation
279 indentSpaces := []string{
280 "",
281 " ",
282 " ",
283 " ",
284 " ",
285 " ",
286 " ",
287 " ",
288 " ",
289 " ",
290 }
291
292 // indent a specified number of spaces
293 doIndent := func(indt int) {
294 i := indt
295 for i > 9 {
296 proc(" ")
297 i -= 10
298 }
299 if i < 0 {
300 return
301 }
302 proc(indentSpaces[i])
303 }
304
305 afix := strings.NewReplacer(
306 "&lt;", "<",
307 "&gt;", ">",
308 "&amp;", "&",
309 "&apos;", "'",
310 "&#39;", "'",
311 "&quot;", "'",
312 "&#34;", "'",
313 "\"", "'",
314 )
315
316 // doASNtree recursive definition
317 var doASNtree func(*XMLNode, int, bool)
318
319 doASNtree = func(curr *XMLNode, depth int, comma bool) {
320
321 // suppress if it would be an empty self-closing tag
322 if !IsNotJustWhitespace(curr.Attributes) && curr.Contents == "" && curr.Children == nil {
323 return
324 }
325
326 name := curr.Name
327 if name == "" {
328 name = "_"
329 }
330
331 // leading underscore - unnamed braces (element of SEQUENCE OF or SET OF structured objects)
332 // trailing underscore - unquoted value
333 // internal underscore - convert to space
334 show := true
335 quot := true
336 if strings.HasPrefix(name, "_") {
337 show = false
338 } else if strings.HasSuffix(name, "_") {
339 name = strings.TrimSuffix(name, "_")
340 quot = false
341 }
342 name = strings.Replace(name, "_", " ", -1)
343
344 if curr.Contents != "" {
345
346 doIndent(depth)
347 proc(name)
348 proc(" ")
349 if quot {
350 proc("\"")
351 }
352
353 str := curr.Contents[:]
354 if HasBadSpace(str) {
355 str = CleanupBadSpaces(str)
356 }
357 if IsNotASCII(str) {
358 str = TransformAccents(str, false, false)
359 }
360 if HasAdjacentSpaces(str) {
361 str = CompressRunsOfSpaces(str)
362 }
363 str = afix.Replace(str)
364 proc(str)
365
366 if quot {
367 proc("\"")
368 }
369
370 } else {
371
372 doIndent(depth)
373 if show {
374 proc(name)
375 proc(" ")
376 }
377 if depth == 0 {
378 proc("::= ")
379 }
380 proc("{\n")
381
382 for chld := curr.Children; chld != nil; chld = chld.Next {
383 // do not print comma after last child object in chain
384 doASNtree(chld, depth+1, (chld.Next != nil))
385 }
386
387 doIndent(depth)
388 proc("}")
389 }
390
391 if comma {
392 proc(",")
393 }
394 proc("\n")
395 }
396
397 doASNtree(node, 0, false)
398 }
399
400 // XMLDoctypeGzipLen is length of gzipped xml + DOCTYPE header, added as separate gzip packet in front of each compressed record
401 const XMLDoctypeGzipLen = 183
402
403 // CreateStashers saves records to archive, multithreaded for performance, use of UID
404 // position index allows it to prevent earlier version from overwriting later version
405 func CreateStashers(stsh, parent, indx, pfx, sfx, db, xmlString string, transform map[string]string, hash, zipp, asn bool, report int, inp <-chan XMLRecord) <-chan string {
406
407 if inp == nil {
408 return nil
409 }
410
411 out := make(chan string, chanDepth)
412 if out == nil {
413 DisplayError("Unable to create stasher channel")
414 os.Exit(1)
415 }
416
417 find := ParseIndex(indx)
418
419 if zipp {
420 sfx += ".gz"
421 }
422
423 type StasherType int
424
425 const (
426 OKAY StasherType = iota
427 WAIT
428 BAIL
429 )
430
431 // mutex to protect access to inUse map
432 var wlock sync.Mutex
433
434 // map to track files currently being written
435 inUse := make(map[string]int)
436
437 // lockFile function prevents colliding writes
438 lockFile := func(id string, index int) StasherType {
439
440 // map is non-reentrant, protect with mutex
441 wlock.Lock()
442
443 // multiple return paths, schedule the unlock command up front
444 defer wlock.Unlock()
445
446 idx, ok := inUse[id]
447
448 if ok {
449 if index < idx {
450 // later version is being written by another goroutine, skip this
451 return BAIL
452 }
453 // earlier version is being written by another goroutine, wait
454 return WAIT
455 }
456
457 // okay to write file, mark in use to prevent collision
458 inUse[id] = index
459 return OKAY
460 }
461
462 // freeFile function removes entry from inUse map
463 freeFile := func(id string) {
464
465 wlock.Lock()
466
467 // free entry in map, later versions of same record can now be written
468 delete(inUse, id)
469
470 wlock.Unlock()
471 }
472
473 // mutex to protect access to rollingCount variable
474 var tlock sync.Mutex
475
476 rollingCount := 0
477
478 countSuccess := func() {
479
480 tlock.Lock()
481
482 rollingCount++
483 if rollingCount >= report {
484 rollingCount = 0
485 // print dot (progress monitor)
486 fmt.Fprintf(os.Stderr, ".")
487 }
488
489 tlock.Unlock()
490 }
491
492 var xmlDoctype []byte
493
494 // make gzip-compressed byte array of xml + DOCTYPE header
495 if xmlString != "" {
496 xmlDoctype = GzipString(xmlString)
497 }
498
499 if db == "pubmed" {
500
501 // reality check on expected length
502 pmaHeadLen := len(xmlDoctype)
503 // if it changes due to a new release date, or new gzip software,
504 // delete the Archive, remove Pubmed sentinel files, update constant
505 // in source code, and reindex
506 if pmaHeadLen != XMLDoctypeGzipLen {
507 fmt.Fprintf(os.Stdout, "Unexpected xmlDoctype length %d\n\n", pmaHeadLen)
508 }
509 }
510
511 // stashRecord saves individual XML record to archive file accessed by trie
512 stashRecord := func(str, id string, index int) string {
513
514 pos := strings.Index(id, ".")
515 if pos >= 0 {
516 // remove version from UID
517 id = id[:pos]
518 }
519
520 dir, file := ArchiveTrie(id)
521
522 if dir == "" || file == "" {
523 return ""
524 }
525
526 if asn {
527 // convert customized XML to ASN.1 before saving
528 curr := ParseRecord(str, parent)
529
530 var buffer strings.Builder
531
532 mapXMLtoASN(curr,
533 func(str string) {
534 if str != "" {
535 buffer.WriteString(str)
536 }
537 })
538
539 txt := buffer.String()
540 if txt != "" {
541 if strings.HasSuffix(txt, "\n") {
542 txt = strings.TrimSuffix(txt, "\n")
543 }
544 }
545 str = txt
546 } else if db == "pmc" {
547 // for XML, add trailing newline, needed for streaming without decompressing
548 if !strings.HasSuffix(str, "\n") {
549 str += "\n"
550 }
551 } else {
552 // for XML, add trailing newline, needed for streaming without decompressing
553 if !strings.HasSuffix(str, "\n") {
554 str += "\n"
555 }
556 }
557
558 attempts := 5
559 keepChecking := true
560
561 for keepChecking {
562 // check if file is not being written by another goroutine
563 switch lockFile(id, index) {
564 case OKAY:
565 // okay to save this record now
566 keepChecking = false
567 case WAIT:
568 // earlier version is being saved, wait one second and try again
569 time.Sleep(time.Second)
570 attempts--
571 if attempts < 1 {
572 // could not get lock after several attempts
573 DisplayError("Unable to save '%s'", id)
574 return ""
575 }
576 case BAIL:
577 // later version is being saved, skip this one
578 return ""
579 default:
580 }
581 }
582
583 // delete lock after writing file
584 defer freeFile(id)
585
586 dpath := filepath.Join(stsh, dir)
587 if dpath == "" {
588 return ""
589 }
590 err := os.MkdirAll(dpath, os.ModePerm)
591 if err != nil {
592 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
593 return ""
594 }
595 fpath := filepath.Join(dpath, pfx+file+sfx)
596 if fpath == "" {
597 return ""
598 }
599
600 // overwrites and truncates existing file
601 fl, err := os.Create(fpath)
602 if err != nil {
603 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
604 return ""
605 }
606
607 res := id
608
609 if hash {
610 // calculate hash code for verification table
611 hsh := crc32.NewIEEE()
612 hsh.Write([]byte(str))
613 val := hsh.Sum32()
614 res = strconv.FormatUint(uint64(val), 10)
615 }
616
617 if zipp {
618
619 if !asn && db == "pubmed" {
620 fl.Write(xmlDoctype)
621 }
622
623 zp := GzipString(str)
624 fl.Write(zp)
625
626 } else {
627
628 // copy uncompressed record to file
629 fl.WriteString(str)
630 if !strings.HasSuffix(str, "\n") {
631 fl.WriteString("\n")
632 }
633 }
634
635 // fl.Sync()
636
637 err = fl.Close()
638 if err != nil {
639 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
640 return ""
641 }
642
643 // progress monitor prints dot every 1000 (.xml or .asn) or 50000 (.e2x) records
644 countSuccess()
645
646 return res
647 }
648
649 // xmlStasher reads from channel and calls stashRecord
650 xmlStasher := func(wg *sync.WaitGroup, inp <-chan XMLRecord, out chan<- string) {
651
652 defer wg.Done()
653
654 for ext := range inp {
655
656 ident := FindIdentifier(ext.Text, parent, find)
657
658 // optional lookup of integer identifier from accession.version string
659 txt, found := transform[ident]
660 if found {
661 ident = txt
662 }
663
664 ext.Ident = ident
665
666 // skip BioC records with explicit 'unknown' identifier
667 if ext.Ident == "unknown" {
668 continue
669 }
670
671 hsh := stashRecord(ext.Text, ext.Ident, ext.Index)
672
673 res := ext.Ident
674 if hash {
675 res += "\t" + hsh
676 }
677 res += "\n"
678
679 runtime.Gosched()
680
681 out <- res
682 }
683 }
684
685 var wg sync.WaitGroup
686
687 // launch multiple stasher goroutines
688 for range numServe {
689 wg.Add(1)
690 go xmlStasher(&wg, inp, out)
691 }
692
693 // launch separate anonymous goroutine to wait until all stashers are done
694 go func() {
695 wg.Wait()
696 close(out)
697 // print newline after rows of dots (progress monitor)
698 fmt.Fprintf(os.Stderr, "\n")
699 }()
700
701 return out
702 }
703
704 // CreateDeleter reads PMIDs, deletes them in the archive, and sends them
705 // down a channel to have the affected inverted index cache files removed.
706 func CreateDeleter(stsh, db string, in io.Reader) <-chan string {
707
708 if stsh == "" || in == nil {
709 return nil
710 }
711
712 out := make(chan string, chanDepth)
713 if out == nil {
714 DisplayError("Unable to create deleter channel")
715 os.Exit(1)
716 }
717
718 recordDeleter := func(in io.Reader, out chan<- string) {
719
720 // close channel when all records have been processed
721 defer close(out)
722
723 scanr := bufio.NewScanner(in)
724
725 verbose := false
726 // set verbose flag from environment variable
727 env := os.Getenv("EDIRECT_LOCAL_VERBOSE")
728 if env == "Y" || env == "y" || env == "true" {
729 verbose = true
730 }
731
732 for scanr.Scan() {
733
734 // read lines of identifiers
735 id := scanr.Text()
736
737 id = strings.TrimPrefix(id, "PMC")
738 id = strings.TrimSuffix(id, "\n")
739
740 pos := strings.Index(id, ".")
741 if pos >= 0 {
742 // remove version suffix
743 id = id[:pos]
744 }
745
746 dir, file := ArchiveTrie(id)
747
748 if dir == "" || file == "" {
749 continue
750 }
751
752 dpath := filepath.Join(stsh, dir, file+".xml.gz")
753 if dpath == "" {
754 continue
755 }
756
757 os.Remove(dpath)
758 if verbose {
759 fmt.Fprintf(os.Stderr, "DEL PMD %s\n", dpath)
760 }
761
762 out <- id
763 }
764 }
765
766 // launch single deleter goroutine
767 go recordDeleter(in, out)
768
769 return out
770 }
771
772 // CreateClearer clears incremental index files whose underlying records have changed
773 func CreateClearer(indexBase, invertBase, db string, inp <-chan string) <-chan string {
774
775 if inp == nil {
776 return nil
777 }
778
779 out := make(chan string, chanDepth)
780 if out == nil {
781 DisplayError("Unable to create clearer channel")
782 os.Exit(1)
783 }
784
785 // maps to track index and inverted files that were deleted
786 deletedIdx := make(map[string]bool)
787
788 deletedInv := make(map[string]bool)
789
790 clearStaleIndices := func(inp <-chan string, out chan<- string) {
791
792 // close channel when all records have been processed
793 defer close(out)
794
795 verbose := false
796 // set verbose flag from environment variable
797 env := os.Getenv("EDIRECT_LOCAL_VERBOSE")
798 if env == "Y" || env == "y" || env == "true" {
799 verbose = true
800 }
801
802 for id := range inp {
803
804 id = strings.TrimPrefix(id, "PMC")
805 id = strings.TrimSuffix(id, "\n")
806
807 pos := strings.Index(id, ".")
808 if pos >= 0 {
809 // remove version from UID
810 id = id[:pos]
811 }
812
813 xdir, idx := IndexTrie(id)
814 if xdir == "" || idx == "" {
815 continue
816 }
817
818 xpath := filepath.Join(indexBase, xdir, idx+".e2x.gz")
819 deletedIdx[xpath] = true
820
821 vdir, inv := InvertTrie(id)
822 if vdir == "" || inv == "" {
823 continue
824 }
825
826 vpath := filepath.Join(invertBase, vdir, inv+".inv.gz")
827 deletedInv[vpath] = true
828
829 out <- id
830 }
831
832 // read (uniqued) maps and delete stale index and inverted files
833 for str := range deletedIdx {
834
835 os.Remove(str)
836 if verbose {
837 fmt.Fprintf(os.Stderr, "DEL IDX %s\n", str)
838 }
839 }
840
841 for str := range deletedInv {
842
843 os.Remove(str)
844 if verbose {
845 fmt.Fprintf(os.Stderr, "DEL INV %s\n", str)
846 }
847 }
848 }
849
850 // launch single clearer goroutine
851 go clearStaleIndices(inp, out)
852
853 return out
854 }
855
856 // CreateFetchers returns uncompressed records from archive, multithreaded for speed
857 func CreateFetchers(stsh, db, pfx, sfx, ptrn string, zipp bool, inp <-chan XMLRecord) <-chan XMLRecord {
858
859 if inp == nil || stsh == "" {
860 return nil
861 }
862
863 // obtain path from environment variable
864 archiveBase := GetLocalArchiveFolder(db, "Archive", true)
865
866 if archiveBase == "" {
867 DisplayError("Unable to get local archive path")
868 os.Exit(1)
869 }
870
871 // check to make sure local archive is mounted
872 _, err := os.Stat(archiveBase)
873 if err != nil && os.IsNotExist(err) {
874 DisplayError("Local archive is not mounted")
875 os.Exit(1)
876 }
877
878 out := make(chan XMLRecord, chanDepth)
879 if out == nil {
880 DisplayError("Unable to create fetcher channel")
881 os.Exit(1)
882 }
883
884 // xmlFetcher reads XML from file
885 xmlFetcher := func(wg *sync.WaitGroup, inp <-chan XMLRecord, out chan<- XMLRecord) {
886
887 // report when more records to process
888 defer wg.Done()
889
890 var buf bytes.Buffer
891
892 for ext := range inp {
893
894 buf.Reset()
895
896 str := fetchOneXMLRecord(ext.Text, stsh, pfx, sfx, zipp, buf)
897
898 // trim any header included in archive XML file
899 if str != "" && ptrn != "" {
900 pos := strings.Index(str, "<"+ptrn+">")
901 if pos > 0 {
902 // remove any leading xml and DOCTYPE lines
903 str = str[pos:]
904 }
905 }
906
907 runtime.Gosched()
908
909 out <- XMLRecord{Index: ext.Index, Ident: ext.Ident, Text: str}
910 }
911 }
912
913 var wg sync.WaitGroup
914
915 // launch multiple fetcher goroutines
916 for range numServe {
917 wg.Add(1)
918 go xmlFetcher(&wg, inp, out)
919 }
920
921 // launch separate anonymous goroutine to wait until all fetchers are done
922 go func() {
923 wg.Wait()
924 close(out)
925 }()
926
927 return out
928 }
929
930 // CreateCacheStreamers returns compressed records from archive, multithreaded for speed,
931 // could be used for sending records over network to be decompressed later by client
932 func CreateCacheStreamers(stsh, db, pfx, sfx string, skip int, inp <-chan XMLRecord) <-chan XMLRecord {
933
934 if inp == nil || stsh == "" {
935 return nil
936 }
937
938 // obtain path from environment variable
939 archiveBase := GetLocalArchiveFolder(db, "Archive", true)
940
941 if archiveBase == "" {
942 DisplayError("Unable to get local archive path")
943 os.Exit(1)
944 }
945
946 // check to make sure local archive is mounted
947 _, err := os.Stat(archiveBase)
948 if err != nil && os.IsNotExist(err) {
949 DisplayError("Local archive is not mounted")
950 os.Exit(1)
951 }
952
953 out := make(chan XMLRecord, chanDepth)
954 if out == nil {
955 DisplayError("Unable to create streamer channel")
956 os.Exit(1)
957 }
958 sfx += ".gz"
959
960 getRecord := func(id string, buf bytes.Buffer) []byte {
961
962 if id == "" {
963 return nil
964 }
965
966 dir, file := ArchiveTrie(id)
967
968 if dir == "" || file == "" {
969 return nil
970 }
971
972 fpath := filepath.Join(stsh, dir, pfx+file+sfx)
973 if fpath == "" {
974 return nil
975 }
976
977 inFile, err := os.Open(fpath)
978
979 if err != nil {
980 msg := err.Error()
981 if !strings.HasSuffix(msg, "no such file or directory") && !strings.HasSuffix(msg, "cannot find the path specified.") {
982 fmt.Fprintf(os.Stderr, "%s\n", msg)
983 }
984 return nil
985 }
986
987 brd := bufio.NewReader(inFile)
988
989 // copy cached file contents
990 buf.ReadFrom(brd)
991
992 data := buf.Bytes()
993
994 inFile.Close()
995
996 return data
997 }
998
999 // xmlStreamer reads compressed XML from file
1000 xmlStreamer := func(wg *sync.WaitGroup, inp <-chan XMLRecord, out chan<- XMLRecord) {
1001
1002 // report when more records to process
1003 defer wg.Done()
1004
1005 var buf bytes.Buffer
1006
1007 for ext := range inp {
1008
1009 buf.Reset()
1010
1011 data := getRecord(ext.Text, buf)
1012
1013 runtime.Gosched()
1014
1015 // skip past first gzip packet with xml and DOCTYPE
1016 if skip > 0 {
1017 if len(data) > skip {
1018 data = data[skip:]
1019 }
1020 } else if db == "pubmed" {
1021 if len(data) > XMLDoctypeGzipLen {
1022 data = data[XMLDoctypeGzipLen:]
1023 }
1024 }
1025
1026 out <- XMLRecord{Index: ext.Index, Ident: ext.Ident, Data: data}
1027 }
1028 }
1029
1030 var wg sync.WaitGroup
1031
1032 // launch multiple streamer goroutines
1033 for range numServe {
1034 wg.Add(1)
1035 go xmlStreamer(&wg, inp, out)
1036 }
1037
1038 // launch separate anonymous goroutine to wait until all streamers are done
1039 go func() {
1040 wg.Wait()
1041 close(out)
1042 }()
1043
1044 return out
1045 }