Log out-of-order tags if -loglevel=debug.
[lightning.git] / import.go
1 package main
2
3 import (
4         "bufio"
5         "compress/gzip"
6         "encoding/gob"
7         "errors"
8         "flag"
9         "fmt"
10         "io"
11         "net/http"
12         _ "net/http/pprof"
13         "os"
14         "os/exec"
15         "path/filepath"
16         "regexp"
17         "runtime"
18         "sort"
19         "strings"
20         "sync"
21         "sync/atomic"
22         "time"
23
24         "git.arvados.org/arvados.git/sdk/go/arvados"
25         log "github.com/sirupsen/logrus"
26 )
27
28 type importer struct {
29         tagLibraryFile string
30         refFile        string
31         outputFile     string
32         projectUUID    string
33         runLocal       bool
34         skipOOO        bool
35         encoder        *gob.Encoder
36 }
37
38 func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
39         var err error
40         defer func() {
41                 if err != nil {
42                         fmt.Fprintf(stderr, "%s\n", err)
43                 }
44         }()
45         flags := flag.NewFlagSet("", flag.ContinueOnError)
46         flags.SetOutput(stderr)
47         flags.StringVar(&cmd.tagLibraryFile, "tag-library", "", "tag library fasta `file`")
48         flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
49         flags.StringVar(&cmd.outputFile, "o", "-", "output `file`")
50         flags.StringVar(&cmd.projectUUID, "project", "", "project `UUID` for output data")
51         flags.BoolVar(&cmd.runLocal, "local", false, "run on local host (default: run in an arvados container)")
52         flags.BoolVar(&cmd.skipOOO, "skip-ooo", false, "skip out-of-order tags")
53         priority := flags.Int("priority", 500, "container request priority")
54         pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
55         loglevel := flags.String("loglevel", "info", "logging threshold (trace, debug, info, warn, error, fatal, or panic)")
56         err = flags.Parse(args)
57         if err == flag.ErrHelp {
58                 err = nil
59                 return 0
60         } else if err != nil {
61                 return 2
62         } else if cmd.tagLibraryFile == "" {
63                 fmt.Fprintln(os.Stderr, "cannot import without -tag-library argument")
64                 return 2
65         } else if flags.NArg() == 0 {
66                 flags.Usage()
67                 return 2
68         }
69
70         if *pprof != "" {
71                 go func() {
72                         log.Println(http.ListenAndServe(*pprof, nil))
73                 }()
74         }
75
76         lvl, err := log.ParseLevel(*loglevel)
77         if err != nil {
78                 return 2
79         }
80         log.SetLevel(lvl)
81
82         if !cmd.runLocal {
83                 runner := arvadosContainerRunner{
84                         Name:        "lightning import",
85                         Client:      arvados.NewClientFromEnv(),
86                         ProjectUUID: cmd.projectUUID,
87                         RAM:         60000000000,
88                         VCPUs:       16,
89                         Priority:    *priority,
90                 }
91                 err = runner.TranslatePaths(&cmd.tagLibraryFile, &cmd.refFile, &cmd.outputFile)
92                 if err != nil {
93                         return 1
94                 }
95                 inputs := flags.Args()
96                 for i := range inputs {
97                         err = runner.TranslatePaths(&inputs[i])
98                         if err != nil {
99                                 return 1
100                         }
101                 }
102                 if cmd.outputFile == "-" {
103                         cmd.outputFile = "/mnt/output/library.gob"
104                 } else {
105                         // Not yet implemented, but this should write
106                         // the collection to an existing collection,
107                         // possibly even an in-place update.
108                         err = errors.New("cannot specify output file in container mode: not implemented")
109                         return 1
110                 }
111                 runner.Args = append([]string{"import", "-local=true", "-loglevel=" + *loglevel, fmt.Sprintf("-skip-ooo=%v", cmd.skipOOO), "-tag-library", cmd.tagLibraryFile, "-ref", cmd.refFile, "-o", cmd.outputFile}, inputs...)
112                 var output string
113                 output, err = runner.Run()
114                 if err != nil {
115                         return 1
116                 }
117                 fmt.Fprintln(stdout, output+"/library.gob")
118                 return 0
119         }
120
121         infiles, err := listInputFiles(flags.Args())
122         if err != nil {
123                 return 1
124         }
125
126         tilelib, err := cmd.loadTileLibrary()
127         if err != nil {
128                 return 1
129         }
130         go func() {
131                 for range time.Tick(10 * time.Minute) {
132                         log.Printf("tilelib.Len() == %d", tilelib.Len())
133                 }
134         }()
135
136         var output io.WriteCloser
137         if cmd.outputFile == "-" {
138                 output = nopCloser{stdout}
139         } else {
140                 output, err = os.OpenFile(cmd.outputFile, os.O_CREATE|os.O_WRONLY, 0777)
141                 if err != nil {
142                         return 1
143                 }
144                 defer output.Close()
145         }
146         bufw := bufio.NewWriter(output)
147         cmd.encoder = gob.NewEncoder(bufw)
148
149         err = cmd.tileInputs(tilelib, infiles)
150         if err != nil {
151                 return 1
152         }
153         err = bufw.Flush()
154         if err != nil {
155                 return 1
156         }
157         err = output.Close()
158         if err != nil {
159                 return 1
160         }
161         return 0
162 }
163
164 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, error) {
165         var input io.ReadCloser
166         input, err := os.Open(infile)
167         if err != nil {
168                 return nil, err
169         }
170         defer input.Close()
171         if strings.HasSuffix(infile, ".gz") {
172                 input, err = gzip.NewReader(input)
173                 if err != nil {
174                         return nil, err
175                 }
176                 defer input.Close()
177         }
178         return tilelib.TileFasta(infile, input)
179 }
180
181 func (cmd *importer) loadTileLibrary() (*tileLibrary, error) {
182         log.Printf("tag library %s load starting", cmd.tagLibraryFile)
183         f, err := os.Open(cmd.tagLibraryFile)
184         if err != nil {
185                 return nil, err
186         }
187         defer f.Close()
188         var rdr io.ReadCloser = f
189         if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
190                 rdr, err = gzip.NewReader(f)
191                 if err != nil {
192                         return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
193                 }
194                 defer rdr.Close()
195         }
196         var taglib tagLibrary
197         err = taglib.Load(rdr)
198         if err != nil {
199                 return nil, err
200         }
201         if taglib.Len() < 1 {
202                 return nil, fmt.Errorf("cannot tile: tag library is empty")
203         }
204         log.Printf("tag library %s load done", cmd.tagLibraryFile)
205         return &tileLibrary{taglib: &taglib, skipOOO: cmd.skipOOO}, nil
206 }
207
208 func listInputFiles(paths []string) (files []string, err error) {
209         for _, path := range paths {
210                 if fi, err := os.Stat(path); err != nil {
211                         return nil, fmt.Errorf("%s: stat failed: %s", path, err)
212                 } else if !fi.IsDir() {
213                         if !strings.HasSuffix(path, ".2.fasta") || strings.HasSuffix(path, ".2.fasta.gz") {
214                                 files = append(files, path)
215                         }
216                         continue
217                 }
218                 d, err := os.Open(path)
219                 if err != nil {
220                         return nil, fmt.Errorf("%s: open failed: %s", path, err)
221                 }
222                 defer d.Close()
223                 names, err := d.Readdirnames(0)
224                 if err != nil {
225                         return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
226                 }
227                 sort.Strings(names)
228                 for _, name := range names {
229                         if strings.HasSuffix(name, ".vcf") || strings.HasSuffix(name, ".vcf.gz") {
230                                 files = append(files, filepath.Join(path, name))
231                         } else if strings.HasSuffix(name, ".1.fasta") || strings.HasSuffix(name, ".1.fasta.gz") {
232                                 files = append(files, filepath.Join(path, name))
233                         }
234                 }
235                 d.Close()
236         }
237         for _, file := range files {
238                 if strings.HasSuffix(file, ".1.fasta") || strings.HasSuffix(file, ".1.fasta.gz") {
239                         continue
240                 } else if _, err := os.Stat(file + ".csi"); err == nil {
241                         continue
242                 } else if _, err = os.Stat(file + ".tbi"); err == nil {
243                         continue
244                 } else {
245                         return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
246                 }
247         }
248         return
249 }
250
251 func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
252         starttime := time.Now()
253         errs := make(chan error, 1)
254         todo := make(chan func() error, len(infiles)*2)
255         var encodeJobs sync.WaitGroup
256         for _, infile := range infiles {
257                 infile := infile
258                 var phases sync.WaitGroup
259                 phases.Add(2)
260                 variants := make([][]tileVariantID, 2)
261                 if strings.HasSuffix(infile, ".1.fasta") || strings.HasSuffix(infile, ".1.fasta.gz") {
262                         todo <- func() error {
263                                 defer phases.Done()
264                                 log.Printf("%s starting", infile)
265                                 defer log.Printf("%s done", infile)
266                                 tseqs, err := cmd.tileFasta(tilelib, infile)
267                                 variants[0] = tseqs.Variants()
268                                 return err
269                         }
270                         infile2 := regexp.MustCompile(`\.1\.fasta(\.gz)?$`).ReplaceAllString(infile, `.2.fasta$1`)
271                         todo <- func() error {
272                                 defer phases.Done()
273                                 log.Printf("%s starting", infile2)
274                                 defer log.Printf("%s done", infile2)
275                                 tseqs, err := cmd.tileFasta(tilelib, infile2)
276                                 variants[1] = tseqs.Variants()
277                                 return err
278                         }
279                 } else {
280                         for phase := 0; phase < 2; phase++ {
281                                 phase := phase
282                                 todo <- func() error {
283                                         defer phases.Done()
284                                         log.Printf("%s phase %d starting", infile, phase+1)
285                                         defer log.Printf("%s phase %d done", infile, phase+1)
286                                         tseqs, err := cmd.tileGVCF(tilelib, infile, phase)
287                                         variants[phase] = tseqs.Variants()
288                                         return err
289                                 }
290                         }
291                 }
292                 encodeJobs.Add(1)
293                 go func() {
294                         defer encodeJobs.Done()
295                         phases.Wait()
296                         if len(errs) > 0 {
297                                 return
298                         }
299                         ntags := len(variants[0])
300                         if ntags < len(variants[1]) {
301                                 ntags = len(variants[1])
302                         }
303                         flat := make([]tileVariantID, ntags*2)
304                         for i := 0; i < ntags; i++ {
305                                 for hap := 0; hap < 2; hap++ {
306                                         if i < len(variants[hap]) {
307                                                 flat[i*2+hap] = variants[hap][i]
308                                         }
309                                 }
310                         }
311                         err := cmd.encoder.Encode(LibraryEntry{
312                                 CompactGenomes: []CompactGenome{{Name: infile, Variants: flat}},
313                         })
314                         if err != nil {
315                                 select {
316                                 case errs <- err:
317                                 default:
318                                 }
319                         }
320                 }()
321         }
322         go close(todo)
323         var tileJobs sync.WaitGroup
324         var running int64
325         for i := 0; i < runtime.NumCPU()*9/8+1; i++ {
326                 tileJobs.Add(1)
327                 atomic.AddInt64(&running, 1)
328                 go func() {
329                         defer tileJobs.Done()
330                         defer atomic.AddInt64(&running, -1)
331                         for fn := range todo {
332                                 if len(errs) > 0 {
333                                         return
334                                 }
335                                 err := fn()
336                                 if err != nil {
337                                         select {
338                                         case errs <- err:
339                                         default:
340                                         }
341                                 }
342                                 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
343                                 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
344                                 eta := time.Now().Add(ttl)
345                                 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
346                         }
347                 }()
348         }
349         tileJobs.Wait()
350         encodeJobs.Wait()
351         go close(errs)
352         return <-errs
353 }
354
355 func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, err error) {
356         if cmd.refFile == "" {
357                 err = errors.New("cannot import vcf: reference data (-ref) not specified")
358                 return
359         }
360         args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
361         indexsuffix := ".tbi"
362         if _, err := os.Stat(infile + ".csi"); err == nil {
363                 indexsuffix = ".csi"
364         }
365         if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
366                 args = append([]string{
367                         "docker", "run", "--rm",
368                         "--log-driver=none",
369                         "--volume=" + infile + ":" + infile + ":ro",
370                         "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
371                         "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
372                         "lightning-runtime",
373                 }, args...)
374         }
375         consensus := exec.Command(args[0], args[1:]...)
376         consensus.Stderr = os.Stderr
377         stdout, err := consensus.StdoutPipe()
378         defer stdout.Close()
379         if err != nil {
380                 return
381         }
382         err = consensus.Start()
383         if err != nil {
384                 return
385         }
386         defer consensus.Wait()
387         tileseq, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout)
388         if err != nil {
389                 return
390         }
391         err = stdout.Close()
392         if err != nil {
393                 return
394         }
395         err = consensus.Wait()
396         if err != nil {
397                 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)
398                 return
399         }
400         return
401 }